blob: ad76012f484e7dba6630ba94dffbcfef65a9ce71 [file] [log] [blame]
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001/*
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 */
16package android.net;
17
18import static android.annotation.SystemApi.Client.MODULE_LIBRARIES;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080019import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_1;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090020import static android.net.NetworkRequest.Type.BACKGROUND_REQUEST;
21import static android.net.NetworkRequest.Type.LISTEN;
junyulai7664f622021-03-12 20:05:08 +080022import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090023import static android.net.NetworkRequest.Type.REQUEST;
24import static android.net.NetworkRequest.Type.TRACK_DEFAULT;
Lorenzo Colittia77d05e2021-01-29 20:14:04 +090025import static android.net.NetworkRequest.Type.TRACK_SYSTEM_DEFAULT;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090026import static android.net.QosCallback.QosCallbackRegistrationException;
27
28import android.annotation.CallbackExecutor;
Junyu Laidf210362023-10-24 02:47:50 +000029import android.annotation.FlaggedApi;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090030import android.annotation.IntDef;
31import android.annotation.NonNull;
32import android.annotation.Nullable;
Chalard Jean2fb66f12023-08-25 12:50:37 +090033import android.annotation.RequiresApi;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090034import android.annotation.RequiresPermission;
35import android.annotation.SdkConstant;
36import android.annotation.SdkConstant.SdkConstantType;
37import android.annotation.SuppressLint;
38import android.annotation.SystemApi;
39import android.annotation.SystemService;
40import android.app.PendingIntent;
Lorenzo Colitti8ad58122021-03-18 00:54:57 +090041import android.app.admin.DevicePolicyManager;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090042import android.compat.annotation.UnsupportedAppUsage;
Lorenzo Colitti8ad58122021-03-18 00:54:57 +090043import android.content.ComponentName;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090044import android.content.Context;
45import android.content.Intent;
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +090046import android.net.ConnectivityDiagnosticsManager.DataStallReport.DetectionMethod;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090047import android.net.IpSecManager.UdpEncapsulationSocket;
48import android.net.SocketKeepalive.Callback;
49import android.net.TetheringManager.StartTetheringCallback;
50import android.net.TetheringManager.TetheringEventCallback;
51import android.net.TetheringManager.TetheringRequest;
52import android.os.Binder;
53import android.os.Build;
54import android.os.Build.VERSION_CODES;
55import android.os.Bundle;
56import android.os.Handler;
57import android.os.IBinder;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090058import android.os.Looper;
59import android.os.Message;
60import android.os.Messenger;
61import android.os.ParcelFileDescriptor;
62import android.os.PersistableBundle;
63import android.os.Process;
64import android.os.RemoteException;
65import android.os.ResultReceiver;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090066import android.os.ServiceSpecificException;
Chalard Jeanad565e22021-02-25 17:23:40 +090067import android.os.UserHandle;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090068import android.provider.Settings;
69import android.telephony.SubscriptionManager;
70import android.telephony.TelephonyManager;
71import android.util.ArrayMap;
72import android.util.Log;
73import android.util.Range;
74import android.util.SparseIntArray;
75
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090076import com.android.internal.annotations.GuardedBy;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +090077
78import libcore.net.event.NetworkEventDispatcher;
79
80import java.io.IOException;
81import java.io.UncheckedIOException;
82import java.lang.annotation.Retention;
83import java.lang.annotation.RetentionPolicy;
84import java.net.DatagramSocket;
85import java.net.InetAddress;
86import java.net.InetSocketAddress;
87import java.net.Socket;
88import java.util.ArrayList;
89import java.util.Collection;
90import java.util.HashMap;
91import java.util.List;
92import java.util.Map;
93import java.util.Objects;
94import java.util.concurrent.Executor;
95import java.util.concurrent.ExecutorService;
96import java.util.concurrent.Executors;
97import java.util.concurrent.RejectedExecutionException;
98
99/**
100 * Class that answers queries about the state of network connectivity. It also
101 * notifies applications when network connectivity changes.
102 * <p>
103 * The primary responsibilities of this class are to:
104 * <ol>
105 * <li>Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)</li>
106 * <li>Send broadcast intents when network connectivity changes</li>
107 * <li>Attempt to "fail over" to another network when connectivity to a network
108 * is lost</li>
109 * <li>Provide an API that allows applications to query the coarse-grained or fine-grained
110 * state of the available networks</li>
111 * <li>Provide an API that allows applications to request and select networks for their data
112 * traffic</li>
113 * </ol>
114 */
115@SystemService(Context.CONNECTIVITY_SERVICE)
116public class ConnectivityManager {
117 private static final String TAG = "ConnectivityManager";
118 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
119
Junyu Laidf210362023-10-24 02:47:50 +0000120 // TODO : remove this class when udc-mainline-prod is abandoned and android.net.flags.Flags is
121 // available here
122 /** @hide */
123 public static class Flags {
124 static final String SET_DATA_SAVER_VIA_CM =
125 "com.android.net.flags.set_data_saver_via_cm";
126 }
127
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900128 /**
129 * A change in network connectivity has occurred. A default connection has either
130 * been established or lost. The NetworkInfo for the affected network is
131 * sent as an extra; it should be consulted to see what kind of
132 * connectivity event occurred.
133 * <p/>
134 * Apps targeting Android 7.0 (API level 24) and higher do not receive this
135 * broadcast if they declare the broadcast receiver in their manifest. Apps
136 * will still receive broadcasts if they register their
137 * {@link android.content.BroadcastReceiver} with
138 * {@link android.content.Context#registerReceiver Context.registerReceiver()}
139 * and that context is still valid.
140 * <p/>
141 * If this is a connection that was the result of failing over from a
142 * disconnected network, then the FAILOVER_CONNECTION boolean extra is
143 * set to true.
144 * <p/>
145 * For a loss of connectivity, if the connectivity manager is attempting
146 * to connect (or has already connected) to another network, the
147 * NetworkInfo for the new network is also passed as an extra. This lets
148 * any receivers of the broadcast know that they should not necessarily
149 * tell the user that no data traffic will be possible. Instead, the
150 * receiver should expect another broadcast soon, indicating either that
151 * the failover attempt succeeded (and so there is still overall data
152 * connectivity), or that the failover attempt failed, meaning that all
153 * connectivity has been lost.
154 * <p/>
155 * For a disconnect event, the boolean extra EXTRA_NO_CONNECTIVITY
156 * is set to {@code true} if there are no connected networks at all.
Chalard Jean025f40b2021-10-04 18:33:36 +0900157 * <p />
158 * Note that this broadcast is deprecated and generally tries to implement backwards
159 * compatibility with older versions of Android. As such, it may not reflect new
160 * capabilities of the system, like multiple networks being connected at the same
161 * time, the details of newer technology, or changes in tethering state.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900162 *
163 * @deprecated apps should use the more versatile {@link #requestNetwork},
164 * {@link #registerNetworkCallback} or {@link #registerDefaultNetworkCallback}
165 * functions instead for faster and more detailed updates about the network
166 * changes they care about.
167 */
168 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
169 @Deprecated
170 public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
171
172 /**
173 * The device has connected to a network that has presented a captive
174 * portal, which is blocking Internet connectivity. The user was presented
175 * with a notification that network sign in is required,
176 * and the user invoked the notification's action indicating they
177 * desire to sign in to the network. Apps handling this activity should
178 * facilitate signing in to the network. This action includes a
179 * {@link Network} typed extra called {@link #EXTRA_NETWORK} that represents
180 * the network presenting the captive portal; all communication with the
181 * captive portal must be done using this {@code Network} object.
182 * <p/>
183 * This activity includes a {@link CaptivePortal} extra named
184 * {@link #EXTRA_CAPTIVE_PORTAL} that can be used to indicate different
185 * outcomes of the captive portal sign in to the system:
186 * <ul>
187 * <li> When the app handling this action believes the user has signed in to
188 * the network and the captive portal has been dismissed, the app should
189 * call {@link CaptivePortal#reportCaptivePortalDismissed} so the system can
190 * reevaluate the network. If reevaluation finds the network no longer
191 * subject to a captive portal, the network may become the default active
192 * data network.</li>
193 * <li> When the app handling this action believes the user explicitly wants
194 * to ignore the captive portal and the network, the app should call
195 * {@link CaptivePortal#ignoreNetwork}. </li>
196 * </ul>
197 */
198 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
199 public static final String ACTION_CAPTIVE_PORTAL_SIGN_IN = "android.net.conn.CAPTIVE_PORTAL";
200
201 /**
202 * The lookup key for a {@link NetworkInfo} object. Retrieve with
203 * {@link android.content.Intent#getParcelableExtra(String)}.
204 *
205 * @deprecated The {@link NetworkInfo} object is deprecated, as many of its properties
206 * can't accurately represent modern network characteristics.
207 * Please obtain information about networks from the {@link NetworkCapabilities}
208 * or {@link LinkProperties} objects instead.
209 */
210 @Deprecated
211 public static final String EXTRA_NETWORK_INFO = "networkInfo";
212
213 /**
214 * Network type which triggered a {@link #CONNECTIVITY_ACTION} broadcast.
215 *
216 * @see android.content.Intent#getIntExtra(String, int)
217 * @deprecated The network type is not rich enough to represent the characteristics
218 * of modern networks. Please use {@link NetworkCapabilities} instead,
219 * in particular the transports.
220 */
221 @Deprecated
222 public static final String EXTRA_NETWORK_TYPE = "networkType";
223
224 /**
225 * The lookup key for a boolean that indicates whether a connect event
226 * is for a network to which the connectivity manager was failing over
227 * following a disconnect on another network.
228 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
229 *
230 * @deprecated See {@link NetworkInfo}.
231 */
232 @Deprecated
233 public static final String EXTRA_IS_FAILOVER = "isFailover";
234 /**
235 * The lookup key for a {@link NetworkInfo} object. This is supplied when
236 * there is another network that it may be possible to connect to. Retrieve with
237 * {@link android.content.Intent#getParcelableExtra(String)}.
238 *
239 * @deprecated See {@link NetworkInfo}.
240 */
241 @Deprecated
242 public static final String EXTRA_OTHER_NETWORK_INFO = "otherNetwork";
243 /**
244 * The lookup key for a boolean that indicates whether there is a
245 * complete lack of connectivity, i.e., no network is available.
246 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
247 */
248 public static final String EXTRA_NO_CONNECTIVITY = "noConnectivity";
249 /**
250 * The lookup key for a string that indicates why an attempt to connect
251 * to a network failed. The string has no particular structure. It is
252 * intended to be used in notifications presented to users. Retrieve
253 * it with {@link android.content.Intent#getStringExtra(String)}.
254 */
255 public static final String EXTRA_REASON = "reason";
256 /**
257 * The lookup key for a string that provides optionally supplied
258 * extra information about the network state. The information
259 * may be passed up from the lower networking layers, and its
260 * meaning may be specific to a particular network type. Retrieve
261 * it with {@link android.content.Intent#getStringExtra(String)}.
262 *
263 * @deprecated See {@link NetworkInfo#getExtraInfo()}.
264 */
265 @Deprecated
266 public static final String EXTRA_EXTRA_INFO = "extraInfo";
267 /**
268 * The lookup key for an int that provides information about
269 * our connection to the internet at large. 0 indicates no connection,
270 * 100 indicates a great connection. Retrieve it with
271 * {@link android.content.Intent#getIntExtra(String, int)}.
272 * {@hide}
273 */
274 public static final String EXTRA_INET_CONDITION = "inetCondition";
275 /**
276 * The lookup key for a {@link CaptivePortal} object included with the
277 * {@link #ACTION_CAPTIVE_PORTAL_SIGN_IN} intent. The {@code CaptivePortal}
278 * object can be used to either indicate to the system that the captive
279 * portal has been dismissed or that the user does not want to pursue
280 * signing in to captive portal. Retrieve it with
281 * {@link android.content.Intent#getParcelableExtra(String)}.
282 */
283 public static final String EXTRA_CAPTIVE_PORTAL = "android.net.extra.CAPTIVE_PORTAL";
284
285 /**
286 * Key for passing a URL to the captive portal login activity.
287 */
288 public static final String EXTRA_CAPTIVE_PORTAL_URL = "android.net.extra.CAPTIVE_PORTAL_URL";
289
290 /**
291 * Key for passing a {@link android.net.captiveportal.CaptivePortalProbeSpec} to the captive
292 * portal login activity.
293 * {@hide}
294 */
295 @SystemApi
296 public static final String EXTRA_CAPTIVE_PORTAL_PROBE_SPEC =
297 "android.net.extra.CAPTIVE_PORTAL_PROBE_SPEC";
298
299 /**
300 * Key for passing a user agent string to the captive portal login activity.
301 * {@hide}
302 */
303 @SystemApi
304 public static final String EXTRA_CAPTIVE_PORTAL_USER_AGENT =
305 "android.net.extra.CAPTIVE_PORTAL_USER_AGENT";
306
307 /**
308 * Broadcast action to indicate the change of data activity status
309 * (idle or active) on a network in a recent period.
310 * The network becomes active when data transmission is started, or
311 * idle if there is no data transmission for a period of time.
312 * {@hide}
313 */
314 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
315 public static final String ACTION_DATA_ACTIVITY_CHANGE =
316 "android.net.conn.DATA_ACTIVITY_CHANGE";
317 /**
318 * The lookup key for an enum that indicates the network device type on which this data activity
319 * change happens.
320 * {@hide}
321 */
322 public static final String EXTRA_DEVICE_TYPE = "deviceType";
323 /**
324 * The lookup key for a boolean that indicates the device is active or not. {@code true} means
325 * it is actively sending or receiving data and {@code false} means it is idle.
326 * {@hide}
327 */
328 public static final String EXTRA_IS_ACTIVE = "isActive";
329 /**
330 * The lookup key for a long that contains the timestamp (nanos) of the radio state change.
331 * {@hide}
332 */
333 public static final String EXTRA_REALTIME_NS = "tsNanos";
334
335 /**
336 * Broadcast Action: The setting for background data usage has changed
337 * values. Use {@link #getBackgroundDataSetting()} to get the current value.
338 * <p>
339 * If an application uses the network in the background, it should listen
340 * for this broadcast and stop using the background data if the value is
341 * {@code false}.
342 * <p>
343 *
344 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability
345 * of background data depends on several combined factors, and
346 * this broadcast is no longer sent. Instead, when background
347 * data is unavailable, {@link #getActiveNetworkInfo()} will now
348 * appear disconnected. During first boot after a platform
349 * upgrade, this broadcast will be sent once if
350 * {@link #getBackgroundDataSetting()} was {@code false} before
351 * the upgrade.
352 */
353 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
354 @Deprecated
355 public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED =
356 "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
357
358 /**
359 * Broadcast Action: The network connection may not be good
360 * uses {@code ConnectivityManager.EXTRA_INET_CONDITION} and
361 * {@code ConnectivityManager.EXTRA_NETWORK_INFO} to specify
362 * the network and it's condition.
363 * @hide
364 */
365 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
366 @UnsupportedAppUsage
367 public static final String INET_CONDITION_ACTION =
368 "android.net.conn.INET_CONDITION_ACTION";
369
370 /**
371 * Broadcast Action: A tetherable connection has come or gone.
372 * Uses {@code ConnectivityManager.EXTRA_AVAILABLE_TETHER},
373 * {@code ConnectivityManager.EXTRA_ACTIVE_LOCAL_ONLY},
374 * {@code ConnectivityManager.EXTRA_ACTIVE_TETHER}, and
375 * {@code ConnectivityManager.EXTRA_ERRORED_TETHER} to indicate
376 * the current state of tethering. Each include a list of
377 * interface names in that state (may be empty).
378 * @hide
379 */
380 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
381 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
382 public static final String ACTION_TETHER_STATE_CHANGED =
383 TetheringManager.ACTION_TETHER_STATE_CHANGED;
384
385 /**
386 * @hide
387 * gives a String[] listing all the interfaces configured for
388 * tethering and currently available for tethering.
389 */
390 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
391 public static final String EXTRA_AVAILABLE_TETHER = TetheringManager.EXTRA_AVAILABLE_TETHER;
392
393 /**
394 * @hide
395 * gives a String[] listing all the interfaces currently in local-only
396 * mode (ie, has DHCPv4+IPv6-ULA support and no packet forwarding)
397 */
398 public static final String EXTRA_ACTIVE_LOCAL_ONLY = TetheringManager.EXTRA_ACTIVE_LOCAL_ONLY;
399
400 /**
401 * @hide
402 * gives a String[] listing all the interfaces currently tethered
403 * (ie, has DHCPv4 support and packets potentially forwarded/NATed)
404 */
405 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
406 public static final String EXTRA_ACTIVE_TETHER = TetheringManager.EXTRA_ACTIVE_TETHER;
407
408 /**
409 * @hide
410 * gives a String[] listing all the interfaces we tried to tether and
411 * failed. Use {@link #getLastTetherError} to find the error code
412 * for any interfaces listed here.
413 */
414 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
415 public static final String EXTRA_ERRORED_TETHER = TetheringManager.EXTRA_ERRORED_TETHER;
416
417 /**
418 * Broadcast Action: The captive portal tracker has finished its test.
419 * Sent only while running Setup Wizard, in lieu of showing a user
420 * notification.
421 * @hide
422 */
423 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
424 public static final String ACTION_CAPTIVE_PORTAL_TEST_COMPLETED =
425 "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED";
426 /**
427 * The lookup key for a boolean that indicates whether a captive portal was detected.
428 * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
429 * @hide
430 */
431 public static final String EXTRA_IS_CAPTIVE_PORTAL = "captivePortal";
432
433 /**
434 * Action used to display a dialog that asks the user whether to connect to a network that is
435 * not validated. This intent is used to start the dialog in settings via startActivity.
436 *
lucaslin8bee2fd2021-04-21 10:43:15 +0800437 * This action includes a {@link Network} typed extra which is called
438 * {@link ConnectivityManager#EXTRA_NETWORK} that represents the network which is unvalidated.
439 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900440 * @hide
441 */
lucaslincf6d4502021-03-04 17:09:51 +0800442 @SystemApi(client = MODULE_LIBRARIES)
443 public static final String ACTION_PROMPT_UNVALIDATED = "android.net.action.PROMPT_UNVALIDATED";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900444
445 /**
446 * Action used to display a dialog that asks the user whether to avoid a network that is no
447 * longer validated. This intent is used to start the dialog in settings via startActivity.
448 *
lucaslin8bee2fd2021-04-21 10:43:15 +0800449 * This action includes a {@link Network} typed extra which is called
450 * {@link ConnectivityManager#EXTRA_NETWORK} that represents the network which is no longer
451 * validated.
452 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900453 * @hide
454 */
lucaslincf6d4502021-03-04 17:09:51 +0800455 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900456 public static final String ACTION_PROMPT_LOST_VALIDATION =
lucaslincf6d4502021-03-04 17:09:51 +0800457 "android.net.action.PROMPT_LOST_VALIDATION";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900458
459 /**
460 * Action used to display a dialog that asks the user whether to stay connected to a network
461 * that has not validated. This intent is used to start the dialog in settings via
462 * startActivity.
463 *
lucaslin8bee2fd2021-04-21 10:43:15 +0800464 * This action includes a {@link Network} typed extra which is called
465 * {@link ConnectivityManager#EXTRA_NETWORK} that represents the network which has partial
466 * connectivity.
467 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900468 * @hide
469 */
lucaslincf6d4502021-03-04 17:09:51 +0800470 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900471 public static final String ACTION_PROMPT_PARTIAL_CONNECTIVITY =
lucaslincf6d4502021-03-04 17:09:51 +0800472 "android.net.action.PROMPT_PARTIAL_CONNECTIVITY";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900473
474 /**
paulhub49c8422021-04-07 16:18:13 +0800475 * Clear DNS Cache Action: This is broadcast when networks have changed and old
476 * DNS entries should be cleared.
477 * @hide
478 */
479 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
480 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
481 public static final String ACTION_CLEAR_DNS_CACHE = "android.net.action.CLEAR_DNS_CACHE";
482
483 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900484 * Invalid tethering type.
485 * @see #startTethering(int, boolean, OnStartTetheringCallback)
486 * @hide
487 */
488 public static final int TETHERING_INVALID = TetheringManager.TETHERING_INVALID;
489
490 /**
491 * Wifi tethering type.
492 * @see #startTethering(int, boolean, OnStartTetheringCallback)
493 * @hide
494 */
495 @SystemApi
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +0900496 public static final int TETHERING_WIFI = 0;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900497
498 /**
499 * USB tethering type.
500 * @see #startTethering(int, boolean, OnStartTetheringCallback)
501 * @hide
502 */
503 @SystemApi
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +0900504 public static final int TETHERING_USB = 1;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900505
506 /**
507 * Bluetooth tethering type.
508 * @see #startTethering(int, boolean, OnStartTetheringCallback)
509 * @hide
510 */
511 @SystemApi
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +0900512 public static final int TETHERING_BLUETOOTH = 2;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900513
514 /**
515 * Wifi P2p tethering type.
516 * Wifi P2p tethering is set through events automatically, and don't
517 * need to start from #startTethering(int, boolean, OnStartTetheringCallback).
518 * @hide
519 */
520 public static final int TETHERING_WIFI_P2P = TetheringManager.TETHERING_WIFI_P2P;
521
522 /**
523 * Extra used for communicating with the TetherService. Includes the type of tethering to
524 * enable if any.
525 * @hide
526 */
527 public static final String EXTRA_ADD_TETHER_TYPE = TetheringConstants.EXTRA_ADD_TETHER_TYPE;
528
529 /**
530 * Extra used for communicating with the TetherService. Includes the type of tethering for
531 * which to cancel provisioning.
532 * @hide
533 */
534 public static final String EXTRA_REM_TETHER_TYPE = TetheringConstants.EXTRA_REM_TETHER_TYPE;
535
536 /**
537 * Extra used for communicating with the TetherService. True to schedule a recheck of tether
538 * provisioning.
539 * @hide
540 */
541 public static final String EXTRA_SET_ALARM = TetheringConstants.EXTRA_SET_ALARM;
542
543 /**
544 * Tells the TetherService to run a provision check now.
545 * @hide
546 */
547 public static final String EXTRA_RUN_PROVISION = TetheringConstants.EXTRA_RUN_PROVISION;
548
549 /**
550 * Extra used for communicating with the TetherService. Contains the {@link ResultReceiver}
551 * which will receive provisioning results. Can be left empty.
552 * @hide
553 */
554 public static final String EXTRA_PROVISION_CALLBACK =
555 TetheringConstants.EXTRA_PROVISION_CALLBACK;
556
557 /**
558 * The absence of a connection type.
559 * @hide
560 */
561 @SystemApi
562 public static final int TYPE_NONE = -1;
563
564 /**
565 * A Mobile data connection. Devices may support more than one.
566 *
567 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
568 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000569 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900570 */
571 @Deprecated
572 public static final int TYPE_MOBILE = 0;
573
574 /**
575 * A WIFI data connection. Devices may support more than one.
576 *
577 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
578 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000579 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900580 */
581 @Deprecated
582 public static final int TYPE_WIFI = 1;
583
584 /**
585 * An MMS-specific Mobile data connection. This network type may use the
586 * same network interface as {@link #TYPE_MOBILE} or it may use a different
587 * one. This is used by applications needing to talk to the carrier's
588 * Multimedia Messaging Service servers.
589 *
590 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
591 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
592 * provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
593 */
594 @Deprecated
595 public static final int TYPE_MOBILE_MMS = 2;
596
597 /**
598 * A SUPL-specific Mobile data connection. This network type may use the
599 * same network interface as {@link #TYPE_MOBILE} or it may use a different
600 * one. This is used by applications needing to talk to the carrier's
601 * Secure User Plane Location servers for help locating the device.
602 *
603 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
604 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
605 * provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
606 */
607 @Deprecated
608 public static final int TYPE_MOBILE_SUPL = 3;
609
610 /**
611 * A DUN-specific Mobile data connection. This network type may use the
612 * same network interface as {@link #TYPE_MOBILE} or it may use a different
613 * one. This is sometimes by the system when setting up an upstream connection
614 * for tethering so that the carrier is aware of DUN traffic.
615 *
616 * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
617 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
618 * provides the {@link NetworkCapabilities#NET_CAPABILITY_DUN} capability.
619 */
620 @Deprecated
621 public static final int TYPE_MOBILE_DUN = 4;
622
623 /**
624 * A High Priority Mobile data connection. This network type uses the
625 * same network interface as {@link #TYPE_MOBILE} but the routing setup
626 * is different.
627 *
628 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
629 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000630 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900631 */
632 @Deprecated
633 public static final int TYPE_MOBILE_HIPRI = 5;
634
635 /**
636 * A WiMAX data connection.
637 *
638 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
639 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000640 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900641 */
642 @Deprecated
643 public static final int TYPE_WIMAX = 6;
644
645 /**
646 * A Bluetooth data connection.
647 *
648 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
649 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000650 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900651 */
652 @Deprecated
653 public static final int TYPE_BLUETOOTH = 7;
654
655 /**
656 * Fake data connection. This should not be used on shipping devices.
657 * @deprecated This is not used any more.
658 */
659 @Deprecated
660 public static final int TYPE_DUMMY = 8;
661
662 /**
663 * An Ethernet data connection.
664 *
665 * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
666 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
chiachangwang9473c592022-07-15 02:25:52 +0000667 * appropriate network. See {@link NetworkCapabilities} for supported transports.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900668 */
669 @Deprecated
670 public static final int TYPE_ETHERNET = 9;
671
672 /**
673 * Over the air Administration.
674 * @deprecated Use {@link NetworkCapabilities} instead.
675 * {@hide}
676 */
677 @Deprecated
678 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
679 public static final int TYPE_MOBILE_FOTA = 10;
680
681 /**
682 * IP Multimedia Subsystem.
683 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IMS} instead.
684 * {@hide}
685 */
686 @Deprecated
687 @UnsupportedAppUsage
688 public static final int TYPE_MOBILE_IMS = 11;
689
690 /**
691 * Carrier Branded Services.
692 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_CBS} instead.
693 * {@hide}
694 */
695 @Deprecated
696 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
697 public static final int TYPE_MOBILE_CBS = 12;
698
699 /**
700 * A Wi-Fi p2p connection. Only requesting processes will have access to
701 * the peers connected.
702 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_WIFI_P2P} instead.
703 * {@hide}
704 */
705 @Deprecated
706 @SystemApi
707 public static final int TYPE_WIFI_P2P = 13;
708
709 /**
710 * The network to use for initially attaching to the network
711 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
712 * {@hide}
713 */
714 @Deprecated
715 @UnsupportedAppUsage
716 public static final int TYPE_MOBILE_IA = 14;
717
718 /**
719 * Emergency PDN connection for emergency services. This
720 * may include IMS and MMS in emergency situations.
721 * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
722 * {@hide}
723 */
724 @Deprecated
725 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
726 public static final int TYPE_MOBILE_EMERGENCY = 15;
727
728 /**
729 * The network that uses proxy to achieve connectivity.
730 * @deprecated Use {@link NetworkCapabilities} instead.
731 * {@hide}
732 */
733 @Deprecated
734 @SystemApi
735 public static final int TYPE_PROXY = 16;
736
737 /**
738 * A virtual network using one or more native bearers.
739 * It may or may not be providing security services.
740 * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
741 */
742 @Deprecated
743 public static final int TYPE_VPN = 17;
744
745 /**
746 * A network that is exclusively meant to be used for testing
747 *
748 * @deprecated Use {@link NetworkCapabilities} instead.
749 * @hide
750 */
751 @Deprecated
752 public static final int TYPE_TEST = 18; // TODO: Remove this once NetworkTypes are unused.
753
754 /**
755 * @deprecated Use {@link NetworkCapabilities} instead.
756 * @hide
757 */
758 @Deprecated
759 @Retention(RetentionPolicy.SOURCE)
760 @IntDef(prefix = { "TYPE_" }, value = {
761 TYPE_NONE,
762 TYPE_MOBILE,
763 TYPE_WIFI,
764 TYPE_MOBILE_MMS,
765 TYPE_MOBILE_SUPL,
766 TYPE_MOBILE_DUN,
767 TYPE_MOBILE_HIPRI,
768 TYPE_WIMAX,
769 TYPE_BLUETOOTH,
770 TYPE_DUMMY,
771 TYPE_ETHERNET,
772 TYPE_MOBILE_FOTA,
773 TYPE_MOBILE_IMS,
774 TYPE_MOBILE_CBS,
775 TYPE_WIFI_P2P,
776 TYPE_MOBILE_IA,
777 TYPE_MOBILE_EMERGENCY,
778 TYPE_PROXY,
779 TYPE_VPN,
780 TYPE_TEST
781 })
782 public @interface LegacyNetworkType {}
783
784 // Deprecated constants for return values of startUsingNetworkFeature. They used to live
785 // in com.android.internal.telephony.PhoneConstants until they were made inaccessible.
786 private static final int DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE = 0;
787 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED = 1;
788 private static final int DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED = 3;
789
790 /** {@hide} */
791 public static final int MAX_RADIO_TYPE = TYPE_TEST;
792
793 /** {@hide} */
794 public static final int MAX_NETWORK_TYPE = TYPE_TEST;
795
796 private static final int MIN_NETWORK_TYPE = TYPE_MOBILE;
797
798 /**
799 * If you want to set the default network preference,you can directly
800 * change the networkAttributes array in framework's config.xml.
801 *
802 * @deprecated Since we support so many more networks now, the single
803 * network default network preference can't really express
804 * the hierarchy. Instead, the default is defined by the
805 * networkAttributes in config.xml. You can determine
806 * the current value by calling {@link #getNetworkPreference()}
807 * from an App.
808 */
809 @Deprecated
810 public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
811
812 /**
813 * @hide
814 */
815 public static final int REQUEST_ID_UNSET = 0;
816
817 /**
818 * Static unique request used as a tombstone for NetworkCallbacks that have been unregistered.
819 * This allows to distinguish when unregistering NetworkCallbacks those that were never
820 * registered from those that were already unregistered.
821 * @hide
822 */
823 private static final NetworkRequest ALREADY_UNREGISTERED =
824 new NetworkRequest.Builder().clearCapabilities().build();
825
826 /**
827 * A NetID indicating no Network is selected.
828 * Keep in sync with bionic/libc/dns/include/resolv_netid.h
829 * @hide
830 */
831 public static final int NETID_UNSET = 0;
832
833 /**
Sudheer Shanka1d0d9b42021-03-23 08:12:28 +0000834 * Flag to indicate that an app is not subject to any restrictions that could result in its
835 * network access blocked.
836 *
837 * @hide
838 */
839 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
840 public static final int BLOCKED_REASON_NONE = 0;
841
842 /**
843 * Flag to indicate that an app is subject to Battery saver restrictions that would
844 * result in its network access being blocked.
845 *
846 * @hide
847 */
848 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
849 public static final int BLOCKED_REASON_BATTERY_SAVER = 1 << 0;
850
851 /**
852 * Flag to indicate that an app is subject to Doze restrictions that would
853 * result in its network access being blocked.
854 *
855 * @hide
856 */
857 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
858 public static final int BLOCKED_REASON_DOZE = 1 << 1;
859
860 /**
861 * Flag to indicate that an app is subject to App Standby restrictions that would
862 * result in its network access being blocked.
863 *
864 * @hide
865 */
866 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
867 public static final int BLOCKED_REASON_APP_STANDBY = 1 << 2;
868
869 /**
870 * Flag to indicate that an app is subject to Restricted mode restrictions that would
871 * result in its network access being blocked.
872 *
873 * @hide
874 */
875 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
876 public static final int BLOCKED_REASON_RESTRICTED_MODE = 1 << 3;
877
878 /**
Lorenzo Colitti8ad58122021-03-18 00:54:57 +0900879 * Flag to indicate that an app is blocked because it is subject to an always-on VPN but the VPN
880 * is not currently connected.
881 *
882 * @see DevicePolicyManager#setAlwaysOnVpnPackage(ComponentName, String, boolean)
883 *
884 * @hide
885 */
886 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
887 public static final int BLOCKED_REASON_LOCKDOWN_VPN = 1 << 4;
888
889 /**
Robert Horvath2dac9482021-11-15 15:49:37 +0100890 * Flag to indicate that an app is subject to Low Power Standby restrictions that would
891 * result in its network access being blocked.
892 *
893 * @hide
894 */
895 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
896 public static final int BLOCKED_REASON_LOW_POWER_STANDBY = 1 << 5;
897
898 /**
Sudheer Shanka1d0d9b42021-03-23 08:12:28 +0000899 * Flag to indicate that an app is subject to Data saver restrictions that would
900 * result in its metered network access being blocked.
901 *
902 * @hide
903 */
904 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
905 public static final int BLOCKED_METERED_REASON_DATA_SAVER = 1 << 16;
906
907 /**
908 * Flag to indicate that an app is subject to user restrictions that would
909 * result in its metered network access being blocked.
910 *
911 * @hide
912 */
913 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
914 public static final int BLOCKED_METERED_REASON_USER_RESTRICTED = 1 << 17;
915
916 /**
917 * Flag to indicate that an app is subject to Device admin restrictions that would
918 * result in its metered network access being blocked.
919 *
920 * @hide
921 */
922 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
923 public static final int BLOCKED_METERED_REASON_ADMIN_DISABLED = 1 << 18;
924
925 /**
926 * @hide
927 */
928 @Retention(RetentionPolicy.SOURCE)
929 @IntDef(flag = true, prefix = {"BLOCKED_"}, value = {
930 BLOCKED_REASON_NONE,
931 BLOCKED_REASON_BATTERY_SAVER,
932 BLOCKED_REASON_DOZE,
933 BLOCKED_REASON_APP_STANDBY,
934 BLOCKED_REASON_RESTRICTED_MODE,
Lorenzo Colittia1bd6f62021-03-25 23:17:36 +0900935 BLOCKED_REASON_LOCKDOWN_VPN,
Robert Horvath2dac9482021-11-15 15:49:37 +0100936 BLOCKED_REASON_LOW_POWER_STANDBY,
Sudheer Shanka1d0d9b42021-03-23 08:12:28 +0000937 BLOCKED_METERED_REASON_DATA_SAVER,
938 BLOCKED_METERED_REASON_USER_RESTRICTED,
939 BLOCKED_METERED_REASON_ADMIN_DISABLED,
940 })
941 public @interface BlockedReason {}
942
Lorenzo Colitti8ad58122021-03-18 00:54:57 +0900943 /**
944 * Set of blocked reasons that are only applicable on metered networks.
945 *
946 * @hide
947 */
948 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
949 public static final int BLOCKED_METERED_REASON_MASK = 0xffff0000;
950
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900951 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
952 private final IConnectivityManager mService;
Lorenzo Colitti842075e2021-02-04 17:32:07 +0900953
Robert Horvathd945bf02022-01-27 19:55:16 +0100954 // LINT.IfChange(firewall_chain)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +0900955 /**
markchiene1561fa2021-12-09 22:00:56 +0800956 * Firewall chain for device idle (doze mode).
957 * Allowlist of apps that have network access in device idle.
958 * @hide
959 */
960 @SystemApi(client = MODULE_LIBRARIES)
961 public static final int FIREWALL_CHAIN_DOZABLE = 1;
962
963 /**
964 * Firewall chain used for app standby.
965 * Denylist of apps that do not have network access.
966 * @hide
967 */
968 @SystemApi(client = MODULE_LIBRARIES)
969 public static final int FIREWALL_CHAIN_STANDBY = 2;
970
971 /**
972 * Firewall chain used for battery saver.
973 * Allowlist of apps that have network access when battery saver is on.
974 * @hide
975 */
976 @SystemApi(client = MODULE_LIBRARIES)
977 public static final int FIREWALL_CHAIN_POWERSAVE = 3;
978
979 /**
980 * Firewall chain used for restricted networking mode.
981 * Allowlist of apps that have access in restricted networking mode.
982 * @hide
983 */
984 @SystemApi(client = MODULE_LIBRARIES)
985 public static final int FIREWALL_CHAIN_RESTRICTED = 4;
986
Robert Horvath34cba142022-01-27 19:52:43 +0100987 /**
988 * Firewall chain used for low power standby.
989 * Allowlist of apps that have access in low power standby.
990 * @hide
991 */
992 @SystemApi(client = MODULE_LIBRARIES)
993 public static final int FIREWALL_CHAIN_LOW_POWER_STANDBY = 5;
994
Motomu Utsumib08654c2022-05-11 05:56:26 +0000995 /**
Motomu Utsumid9801492022-06-01 13:57:27 +0000996 * Firewall chain used for OEM-specific application restrictions.
Lorenzo Colittif683c402022-08-03 10:40:00 +0900997 *
998 * Denylist of apps that will not have network access due to OEM-specific restrictions. If an
999 * app UID is placed on this chain, and the chain is enabled, the app's packets will be dropped.
1000 *
1001 * All the {@code FIREWALL_CHAIN_OEM_DENY_x} chains are equivalent, and each one is
1002 * independent of the others. The chains can be enabled and disabled independently, and apps can
1003 * be added and removed from each chain independently.
1004 *
1005 * @see #FIREWALL_CHAIN_OEM_DENY_2
1006 * @see #FIREWALL_CHAIN_OEM_DENY_3
Motomu Utsumid9801492022-06-01 13:57:27 +00001007 * @hide
1008 */
Motomu Utsumi62385c82022-06-12 11:37:19 +00001009 @SystemApi(client = MODULE_LIBRARIES)
Motomu Utsumid9801492022-06-01 13:57:27 +00001010 public static final int FIREWALL_CHAIN_OEM_DENY_1 = 7;
1011
1012 /**
1013 * Firewall chain used for OEM-specific application restrictions.
Lorenzo Colittif683c402022-08-03 10:40:00 +09001014 *
1015 * Denylist of apps that will not have network access due to OEM-specific restrictions. If an
1016 * app UID is placed on this chain, and the chain is enabled, the app's packets will be dropped.
1017 *
1018 * All the {@code FIREWALL_CHAIN_OEM_DENY_x} chains are equivalent, and each one is
1019 * independent of the others. The chains can be enabled and disabled independently, and apps can
1020 * be added and removed from each chain independently.
1021 *
1022 * @see #FIREWALL_CHAIN_OEM_DENY_1
1023 * @see #FIREWALL_CHAIN_OEM_DENY_3
Motomu Utsumid9801492022-06-01 13:57:27 +00001024 * @hide
1025 */
Motomu Utsumi62385c82022-06-12 11:37:19 +00001026 @SystemApi(client = MODULE_LIBRARIES)
Motomu Utsumid9801492022-06-01 13:57:27 +00001027 public static final int FIREWALL_CHAIN_OEM_DENY_2 = 8;
1028
Motomu Utsumi1d9054b2022-06-06 07:44:05 +00001029 /**
1030 * Firewall chain used for OEM-specific application restrictions.
Lorenzo Colittif683c402022-08-03 10:40:00 +09001031 *
1032 * Denylist of apps that will not have network access due to OEM-specific restrictions. If an
1033 * app UID is placed on this chain, and the chain is enabled, the app's packets will be dropped.
1034 *
1035 * All the {@code FIREWALL_CHAIN_OEM_DENY_x} chains are equivalent, and each one is
1036 * independent of the others. The chains can be enabled and disabled independently, and apps can
1037 * be added and removed from each chain independently.
1038 *
1039 * @see #FIREWALL_CHAIN_OEM_DENY_1
1040 * @see #FIREWALL_CHAIN_OEM_DENY_2
Motomu Utsumi1d9054b2022-06-06 07:44:05 +00001041 * @hide
1042 */
Motomu Utsumi62385c82022-06-12 11:37:19 +00001043 @SystemApi(client = MODULE_LIBRARIES)
Motomu Utsumi1d9054b2022-06-06 07:44:05 +00001044 public static final int FIREWALL_CHAIN_OEM_DENY_3 = 9;
1045
markchiene1561fa2021-12-09 22:00:56 +08001046 /** @hide */
1047 @Retention(RetentionPolicy.SOURCE)
1048 @IntDef(flag = false, prefix = "FIREWALL_CHAIN_", value = {
1049 FIREWALL_CHAIN_DOZABLE,
1050 FIREWALL_CHAIN_STANDBY,
1051 FIREWALL_CHAIN_POWERSAVE,
Robert Horvath34cba142022-01-27 19:52:43 +01001052 FIREWALL_CHAIN_RESTRICTED,
Motomu Utsumib08654c2022-05-11 05:56:26 +00001053 FIREWALL_CHAIN_LOW_POWER_STANDBY,
Motomu Utsumid9801492022-06-01 13:57:27 +00001054 FIREWALL_CHAIN_OEM_DENY_1,
Motomu Utsumi1d9054b2022-06-06 07:44:05 +00001055 FIREWALL_CHAIN_OEM_DENY_2,
1056 FIREWALL_CHAIN_OEM_DENY_3
markchiene1561fa2021-12-09 22:00:56 +08001057 })
1058 public @interface FirewallChain {}
Robert Horvathd945bf02022-01-27 19:55:16 +01001059 // LINT.ThenChange(packages/modules/Connectivity/service/native/include/Common.h)
markchiene1561fa2021-12-09 22:00:56 +08001060
1061 /**
markchien011a7f52022-03-29 01:07:22 +08001062 * A firewall rule which allows or drops packets depending on existing policy.
1063 * Used by {@link #setUidFirewallRule(int, int, int)} to follow existing policy to handle
1064 * specific uid's packets in specific firewall chain.
markchien3c04e662022-03-22 16:29:56 +08001065 * @hide
1066 */
1067 @SystemApi(client = MODULE_LIBRARIES)
1068 public static final int FIREWALL_RULE_DEFAULT = 0;
1069
1070 /**
markchien011a7f52022-03-29 01:07:22 +08001071 * A firewall rule which allows packets. Used by {@link #setUidFirewallRule(int, int, int)} to
1072 * allow specific uid's packets in specific firewall chain.
markchien3c04e662022-03-22 16:29:56 +08001073 * @hide
1074 */
1075 @SystemApi(client = MODULE_LIBRARIES)
1076 public static final int FIREWALL_RULE_ALLOW = 1;
1077
1078 /**
markchien011a7f52022-03-29 01:07:22 +08001079 * A firewall rule which drops packets. Used by {@link #setUidFirewallRule(int, int, int)} to
1080 * drop specific uid's packets in specific firewall chain.
markchien3c04e662022-03-22 16:29:56 +08001081 * @hide
1082 */
1083 @SystemApi(client = MODULE_LIBRARIES)
1084 public static final int FIREWALL_RULE_DENY = 2;
1085
1086 /** @hide */
1087 @Retention(RetentionPolicy.SOURCE)
1088 @IntDef(flag = false, prefix = "FIREWALL_RULE_", value = {
1089 FIREWALL_RULE_DEFAULT,
1090 FIREWALL_RULE_ALLOW,
1091 FIREWALL_RULE_DENY
1092 })
1093 public @interface FirewallRule {}
1094
1095 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001096 * A kludge to facilitate static access where a Context pointer isn't available, like in the
1097 * case of the static set/getProcessDefaultNetwork methods and from the Network class.
1098 * TODO: Remove this after deprecating the static methods in favor of non-static methods or
1099 * methods that take a Context argument.
1100 */
1101 private static ConnectivityManager sInstance;
1102
1103 private final Context mContext;
1104
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09001105 @GuardedBy("mTetheringEventCallbacks")
1106 private TetheringManager mTetheringManager;
1107
1108 private TetheringManager getTetheringManager() {
1109 synchronized (mTetheringEventCallbacks) {
1110 if (mTetheringManager == null) {
1111 mTetheringManager = mContext.getSystemService(TetheringManager.class);
1112 }
1113 return mTetheringManager;
1114 }
1115 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001116
1117 /**
1118 * Tests if a given integer represents a valid network type.
1119 * @param networkType the type to be tested
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001120 * @return {@code true} if the type is valid, else {@code false}
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001121 * @deprecated All APIs accepting a network type are deprecated. There should be no need to
1122 * validate a network type.
1123 */
1124 @Deprecated
1125 public static boolean isNetworkTypeValid(int networkType) {
1126 return MIN_NETWORK_TYPE <= networkType && networkType <= MAX_NETWORK_TYPE;
1127 }
1128
1129 /**
1130 * Returns a non-localized string representing a given network type.
1131 * ONLY used for debugging output.
1132 * @param type the type needing naming
1133 * @return a String for the given type, or a string version of the type ("87")
1134 * if no name is known.
1135 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1136 * {@hide}
1137 */
1138 @Deprecated
1139 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1140 public static String getNetworkTypeName(int type) {
1141 switch (type) {
1142 case TYPE_NONE:
1143 return "NONE";
1144 case TYPE_MOBILE:
1145 return "MOBILE";
1146 case TYPE_WIFI:
1147 return "WIFI";
1148 case TYPE_MOBILE_MMS:
1149 return "MOBILE_MMS";
1150 case TYPE_MOBILE_SUPL:
1151 return "MOBILE_SUPL";
1152 case TYPE_MOBILE_DUN:
1153 return "MOBILE_DUN";
1154 case TYPE_MOBILE_HIPRI:
1155 return "MOBILE_HIPRI";
1156 case TYPE_WIMAX:
1157 return "WIMAX";
1158 case TYPE_BLUETOOTH:
1159 return "BLUETOOTH";
1160 case TYPE_DUMMY:
1161 return "DUMMY";
1162 case TYPE_ETHERNET:
1163 return "ETHERNET";
1164 case TYPE_MOBILE_FOTA:
1165 return "MOBILE_FOTA";
1166 case TYPE_MOBILE_IMS:
1167 return "MOBILE_IMS";
1168 case TYPE_MOBILE_CBS:
1169 return "MOBILE_CBS";
1170 case TYPE_WIFI_P2P:
1171 return "WIFI_P2P";
1172 case TYPE_MOBILE_IA:
1173 return "MOBILE_IA";
1174 case TYPE_MOBILE_EMERGENCY:
1175 return "MOBILE_EMERGENCY";
1176 case TYPE_PROXY:
1177 return "PROXY";
1178 case TYPE_VPN:
1179 return "VPN";
Junyu Laic9f1ca62022-07-25 16:31:59 +08001180 case TYPE_TEST:
1181 return "TEST";
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001182 default:
1183 return Integer.toString(type);
1184 }
1185 }
1186
1187 /**
1188 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001189 */
lucaslin10774b72021-03-17 14:16:01 +08001190 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001191 public void systemReady() {
1192 try {
1193 mService.systemReady();
1194 } catch (RemoteException e) {
1195 throw e.rethrowFromSystemServer();
1196 }
1197 }
1198
1199 /**
1200 * Checks if a given type uses the cellular data connection.
1201 * This should be replaced in the future by a network property.
1202 * @param networkType the type to check
1203 * @return a boolean - {@code true} if uses cellular network, else {@code false}
1204 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1205 * {@hide}
1206 */
1207 @Deprecated
1208 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
1209 public static boolean isNetworkTypeMobile(int networkType) {
1210 switch (networkType) {
1211 case TYPE_MOBILE:
1212 case TYPE_MOBILE_MMS:
1213 case TYPE_MOBILE_SUPL:
1214 case TYPE_MOBILE_DUN:
1215 case TYPE_MOBILE_HIPRI:
1216 case TYPE_MOBILE_FOTA:
1217 case TYPE_MOBILE_IMS:
1218 case TYPE_MOBILE_CBS:
1219 case TYPE_MOBILE_IA:
1220 case TYPE_MOBILE_EMERGENCY:
1221 return true;
1222 default:
1223 return false;
1224 }
1225 }
1226
1227 /**
1228 * Checks if the given network type is backed by a Wi-Fi radio.
1229 *
1230 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
1231 * @hide
1232 */
1233 @Deprecated
1234 public static boolean isNetworkTypeWifi(int networkType) {
1235 switch (networkType) {
1236 case TYPE_WIFI:
1237 case TYPE_WIFI_P2P:
1238 return true;
1239 default:
1240 return false;
1241 }
1242 }
1243
1244 /**
Junyu Lai35665cc2022-12-19 17:37:48 +08001245 * Preference for {@link ProfileNetworkPreference.Builder#setPreference(int)}.
chiachangwang9473c592022-07-15 02:25:52 +00001246 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
Junyu Lai35665cc2022-12-19 17:37:48 +08001247 * Specify that the traffic for this user should by follow the default rules:
1248 * applications in the profile designated by the UserHandle behave like any
1249 * other application and use the system default network as their default
1250 * network. Compare other PROFILE_NETWORK_PREFERENCE_* settings.
Chalard Jeanad565e22021-02-25 17:23:40 +09001251 * @hide
1252 */
Chalard Jeanbef6b092021-03-17 14:33:24 +09001253 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09001254 public static final int PROFILE_NETWORK_PREFERENCE_DEFAULT = 0;
1255
1256 /**
Junyu Lai35665cc2022-12-19 17:37:48 +08001257 * Preference for {@link ProfileNetworkPreference.Builder#setPreference(int)}.
chiachangwang9473c592022-07-15 02:25:52 +00001258 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
Chalard Jeanad565e22021-02-25 17:23:40 +09001259 * Specify that the traffic for this user should by default go on a network with
1260 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}, and on the system default network
1261 * if no such network is available.
1262 * @hide
1263 */
Chalard Jeanbef6b092021-03-17 14:33:24 +09001264 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09001265 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE = 1;
1266
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001267 /**
Junyu Lai35665cc2022-12-19 17:37:48 +08001268 * Preference for {@link ProfileNetworkPreference.Builder#setPreference(int)}.
chiachangwang9473c592022-07-15 02:25:52 +00001269 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001270 * Specify that the traffic for this user should by default go on a network with
1271 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE} and if no such network is available
Junyu Lai35665cc2022-12-19 17:37:48 +08001272 * should not have a default network at all (that is, network accesses that
1273 * do not specify a network explicitly terminate with an error), even if there
1274 * is a system default network available to apps outside this preference.
1275 * The apps can still use a non-enterprise network if they request it explicitly
1276 * provided that specific network doesn't require any specific permission they
1277 * do not hold.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001278 * @hide
1279 */
1280 @SystemApi(client = MODULE_LIBRARIES)
1281 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK = 2;
1282
Junyu Lai35665cc2022-12-19 17:37:48 +08001283 /**
1284 * Preference for {@link ProfileNetworkPreference.Builder#setPreference(int)}.
1285 * See {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
1286 * Specify that the traffic for this user should by default go on a network with
1287 * {@link NetworkCapabilities#NET_CAPABILITY_ENTERPRISE}.
1288 * If there is no such network, the apps will have no default
1289 * network at all, even if there are available non-enterprise networks on the
1290 * device (that is, network accesses that do not specify a network explicitly
1291 * terminate with an error). Additionally, the designated apps should be
1292 * blocked from using any non-enterprise network even if they specify it
1293 * explicitly, unless they hold specific privilege overriding this (see
1294 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS}).
1295 * @hide
1296 */
1297 @SystemApi(client = MODULE_LIBRARIES)
1298 public static final int PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING = 3;
1299
Chalard Jeanad565e22021-02-25 17:23:40 +09001300 /** @hide */
1301 @Retention(RetentionPolicy.SOURCE)
1302 @IntDef(value = {
1303 PROFILE_NETWORK_PREFERENCE_DEFAULT,
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08001304 PROFILE_NETWORK_PREFERENCE_ENTERPRISE,
1305 PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK
Chalard Jeanad565e22021-02-25 17:23:40 +09001306 })
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08001307 public @interface ProfileNetworkPreferencePolicy {
Chalard Jeanad565e22021-02-25 17:23:40 +09001308 }
1309
1310 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001311 * Specifies the preferred network type. When the device has more
1312 * than one type available the preferred network type will be used.
1313 *
1314 * @param preference the network type to prefer over all others. It is
1315 * unspecified what happens to the old preferred network in the
1316 * overall ordering.
1317 * @deprecated Functionality has been removed as it no longer makes sense,
1318 * with many more than two networks - we'd need an array to express
1319 * preference. Instead we use dynamic network properties of
1320 * the networks to describe their precedence.
1321 */
1322 @Deprecated
1323 public void setNetworkPreference(int preference) {
1324 }
1325
1326 /**
1327 * Retrieves the current preferred network type.
1328 *
1329 * @return an integer representing the preferred network type
1330 *
1331 * @deprecated Functionality has been removed as it no longer makes sense,
1332 * with many more than two networks - we'd need an array to express
1333 * preference. Instead we use dynamic network properties of
1334 * the networks to describe their precedence.
1335 */
1336 @Deprecated
1337 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1338 public int getNetworkPreference() {
1339 return TYPE_NONE;
1340 }
1341
1342 /**
1343 * Returns details about the currently active default data network. When
1344 * connected, this network is the default route for outgoing connections.
1345 * You should always check {@link NetworkInfo#isConnected()} before initiating
1346 * network traffic. This may return {@code null} when there is no default
1347 * network.
1348 * Note that if the default network is a VPN, this method will return the
1349 * NetworkInfo for one of its underlying networks instead, or null if the
1350 * VPN agent did not specify any. Apps interested in learning about VPNs
1351 * should use {@link #getNetworkInfo(android.net.Network)} instead.
1352 *
1353 * @return a {@link NetworkInfo} object for the current default network
1354 * or {@code null} if no default network is currently active
1355 * @deprecated See {@link NetworkInfo}.
1356 */
1357 @Deprecated
1358 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1359 @Nullable
1360 public NetworkInfo getActiveNetworkInfo() {
1361 try {
1362 return mService.getActiveNetworkInfo();
1363 } catch (RemoteException e) {
1364 throw e.rethrowFromSystemServer();
1365 }
1366 }
1367
1368 /**
1369 * Returns a {@link Network} object corresponding to the currently active
1370 * default data network. In the event that the current active default data
1371 * network disconnects, the returned {@code Network} object will no longer
1372 * be usable. This will return {@code null} when there is no default
Chalard Jean0d051512021-09-28 15:31:15 +09001373 * network, or when the default network is blocked.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001374 *
1375 * @return a {@link Network} object for the current default network or
Chalard Jean0d051512021-09-28 15:31:15 +09001376 * {@code null} if no default network is currently active or if
1377 * the default network is blocked for the caller
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001378 */
1379 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1380 @Nullable
1381 public Network getActiveNetwork() {
1382 try {
1383 return mService.getActiveNetwork();
1384 } catch (RemoteException e) {
1385 throw e.rethrowFromSystemServer();
1386 }
1387 }
1388
1389 /**
1390 * Returns a {@link Network} object corresponding to the currently active
1391 * default data network for a specific UID. In the event that the default data
1392 * network disconnects, the returned {@code Network} object will no longer
1393 * be usable. This will return {@code null} when there is no default
1394 * network for the UID.
1395 *
1396 * @return a {@link Network} object for the current default network for the
1397 * given UID or {@code null} if no default network is currently active
lifrdb7d6762021-03-30 21:04:53 +08001398 *
1399 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001400 */
1401 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
1402 @Nullable
1403 public Network getActiveNetworkForUid(int uid) {
1404 return getActiveNetworkForUid(uid, false);
1405 }
1406
1407 /** {@hide} */
1408 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
1409 try {
1410 return mService.getActiveNetworkForUid(uid, ignoreBlocked);
1411 } catch (RemoteException e) {
1412 throw e.rethrowFromSystemServer();
1413 }
1414 }
1415
lucaslin3ba7cc22022-12-19 02:35:33 +00001416 private static UidRange[] getUidRangeArray(@NonNull Collection<Range<Integer>> ranges) {
1417 Objects.requireNonNull(ranges);
1418 final UidRange[] rangesArray = new UidRange[ranges.size()];
1419 int index = 0;
1420 for (Range<Integer> range : ranges) {
1421 rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
1422 }
1423
1424 return rangesArray;
1425 }
1426
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001427 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001428 * Adds or removes a requirement for given UID ranges to use the VPN.
1429 *
1430 * If set to {@code true}, informs the system that the UIDs in the specified ranges must not
1431 * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
1432 * otherwise have permission to bypass the VPN (e.g., because they have the
1433 * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
1434 * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
1435 * set to {@code false}, a previously-added restriction is removed.
1436 * <p>
1437 * Each of the UID ranges specified by this method is added and removed as is, and no processing
1438 * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
1439 * remove a previously-added range, the exact range must be removed as is.
1440 * <p>
1441 * The changes are applied asynchronously and may not have been applied by the time the method
1442 * returns. Apps will be notified about any changes that apply to them via
1443 * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
1444 * effect.
1445 * <p>
lucaslin3ba7cc22022-12-19 02:35:33 +00001446 * This method will block the specified UIDs from accessing non-VPN networks, but does not
1447 * affect what the UIDs get as their default network.
1448 * Compare {@link #setVpnDefaultForUids(String, Collection)}, which declares that the UIDs
1449 * should only have a VPN as their default network, but does not block them from accessing other
1450 * networks if they request them explicitly with the {@link Network} API.
1451 * <p>
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001452 * This method should be called only by the VPN code.
1453 *
1454 * @param ranges the UID ranges to restrict
1455 * @param requireVpn whether the specified UID ranges must use a VPN
1456 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001457 * @hide
1458 */
1459 @RequiresPermission(anyOf = {
1460 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin97fb10a2021-03-22 11:51:27 +08001461 android.Manifest.permission.NETWORK_STACK,
1462 android.Manifest.permission.NETWORK_SETTINGS})
1463 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001464 public void setRequireVpnForUids(boolean requireVpn,
1465 @NonNull Collection<Range<Integer>> ranges) {
1466 Objects.requireNonNull(ranges);
1467 // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
1468 // This method is not necessarily expected to be used outside the system server, so
1469 // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
1470 // stack process, or by tests.
lucaslin3ba7cc22022-12-19 02:35:33 +00001471 final UidRange[] rangesArray = getUidRangeArray(ranges);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001472 try {
1473 mService.setRequireVpnForUids(requireVpn, rangesArray);
1474 } catch (RemoteException e) {
1475 throw e.rethrowFromSystemServer();
1476 }
1477 }
1478
1479 /**
lucaslin3ba7cc22022-12-19 02:35:33 +00001480 * Inform the system that this VPN session should manage the passed UIDs.
1481 *
1482 * A VPN with the specified session ID may call this method to inform the system that the UIDs
1483 * in the specified range are subject to a VPN.
1484 * When this is called, the system will only choose a VPN for the default network of the UIDs in
1485 * the specified ranges.
1486 *
1487 * This method declares that the UIDs in the range will only have a VPN for their default
1488 * network, but does not block the UIDs from accessing other networks (permissions allowing) by
1489 * explicitly requesting it with the {@link Network} API.
1490 * Compare {@link #setRequireVpnForUids(boolean, Collection)}, which does not affect what
1491 * network the UIDs get as default, but will block them from accessing non-VPN networks.
1492 *
1493 * @param session The VPN session which manages the passed UIDs.
1494 * @param ranges The uid ranges which will treat VPN as their only default network.
1495 *
1496 * @hide
1497 */
1498 @RequiresPermission(anyOf = {
1499 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1500 android.Manifest.permission.NETWORK_STACK,
1501 android.Manifest.permission.NETWORK_SETTINGS})
1502 @SystemApi(client = MODULE_LIBRARIES)
1503 public void setVpnDefaultForUids(@NonNull String session,
1504 @NonNull Collection<Range<Integer>> ranges) {
1505 Objects.requireNonNull(ranges);
1506 final UidRange[] rangesArray = getUidRangeArray(ranges);
1507 try {
1508 mService.setVpnNetworkPreference(session, rangesArray);
1509 } catch (RemoteException e) {
1510 throw e.rethrowFromSystemServer();
1511 }
1512 }
1513
1514 /**
chiachangwange0192a72023-02-06 13:25:01 +00001515 * Temporarily set automaticOnOff keeplaive TCP polling alarm timer to 1 second.
1516 *
1517 * TODO: Remove this when the TCP polling design is replaced with callback.
Jean Chalard17cbf062023-02-13 05:07:48 +00001518 * @param timeMs The time of expiry, with System.currentTimeMillis() base. The value should be
1519 * set no more than 5 minutes in the future.
chiachangwange0192a72023-02-06 13:25:01 +00001520 * @hide
1521 */
1522 public void setTestLowTcpPollingTimerForKeepalive(long timeMs) {
1523 try {
1524 mService.setTestLowTcpPollingTimerForKeepalive(timeMs);
1525 } catch (RemoteException e) {
1526 throw e.rethrowFromSystemServer();
1527 }
1528 }
1529
1530 /**
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001531 * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
1532 * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
1533 * but is still supported for backwards compatibility.
1534 * <p>
1535 * This type of VPN is assumed always to use the system default network, and must always declare
1536 * exactly one underlying network, which is the network that was the default when the VPN
1537 * connected.
1538 * <p>
1539 * Calling this method with {@code true} enables legacy behaviour, specifically:
1540 * <ul>
1541 * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
1542 * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
1543 * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
1544 * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
1545 * underlying the VPN.</li>
1546 * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
1547 * similarly replaced by the VPN network state.</li>
1548 * <li>Information on current network interfaces passed to NetworkStatsService will not
1549 * include any VPN interfaces.</li>
1550 * </ul>
1551 *
1552 * @param enabled whether legacy lockdown VPN is enabled or disabled
1553 *
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001554 * @hide
1555 */
1556 @RequiresPermission(anyOf = {
1557 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
lucaslin97fb10a2021-03-22 11:51:27 +08001558 android.Manifest.permission.NETWORK_STACK,
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001559 android.Manifest.permission.NETWORK_SETTINGS})
lucaslin97fb10a2021-03-22 11:51:27 +08001560 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colittic71cff82021-01-15 01:29:01 +09001561 public void setLegacyLockdownVpnEnabled(boolean enabled) {
1562 try {
1563 mService.setLegacyLockdownVpnEnabled(enabled);
1564 } catch (RemoteException e) {
1565 throw e.rethrowFromSystemServer();
1566 }
1567 }
1568
1569 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001570 * Returns details about the currently active default data network for a given uid.
1571 * This is for privileged use only to avoid spying on other apps.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001572 *
1573 * @return a {@link NetworkInfo} object for the current default network
1574 * for the given uid or {@code null} if no default network is
1575 * available for the specified uid.
1576 *
1577 * {@hide}
1578 */
1579 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
1580 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1581 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1582 return getActiveNetworkInfoForUid(uid, false);
1583 }
1584
1585 /** {@hide} */
1586 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
1587 try {
1588 return mService.getActiveNetworkInfoForUid(uid, ignoreBlocked);
1589 } catch (RemoteException e) {
1590 throw e.rethrowFromSystemServer();
1591 }
1592 }
1593
1594 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001595 * Returns connection status information about a particular network type.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001596 *
1597 * @param networkType integer specifying which networkType in
1598 * which you're interested.
1599 * @return a {@link NetworkInfo} object for the requested
1600 * network type or {@code null} if the type is not
1601 * supported by the device. If {@code networkType} is
1602 * TYPE_VPN and a VPN is active for the calling app,
1603 * then this method will try to return one of the
1604 * underlying networks for the VPN or null if the
1605 * VPN agent didn't specify any.
1606 *
1607 * @deprecated This method does not support multiple connected networks
1608 * of the same type. Use {@link #getAllNetworks} and
1609 * {@link #getNetworkInfo(android.net.Network)} instead.
1610 */
1611 @Deprecated
1612 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1613 @Nullable
1614 public NetworkInfo getNetworkInfo(int networkType) {
1615 try {
1616 return mService.getNetworkInfo(networkType);
1617 } catch (RemoteException e) {
1618 throw e.rethrowFromSystemServer();
1619 }
1620 }
1621
1622 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001623 * Returns connection status information about a particular Network.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001624 *
1625 * @param network {@link Network} specifying which network
1626 * in which you're interested.
1627 * @return a {@link NetworkInfo} object for the requested
1628 * network or {@code null} if the {@code Network}
1629 * is not valid.
1630 * @deprecated See {@link NetworkInfo}.
1631 */
1632 @Deprecated
1633 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1634 @Nullable
1635 public NetworkInfo getNetworkInfo(@Nullable Network network) {
1636 return getNetworkInfoForUid(network, Process.myUid(), false);
1637 }
1638
1639 /** {@hide} */
1640 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
1641 try {
1642 return mService.getNetworkInfoForUid(network, uid, ignoreBlocked);
1643 } catch (RemoteException e) {
1644 throw e.rethrowFromSystemServer();
1645 }
1646 }
1647
1648 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001649 * Returns connection status information about all network types supported by the device.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001650 *
1651 * @return an array of {@link NetworkInfo} objects. Check each
1652 * {@link NetworkInfo#getType} for which type each applies.
1653 *
1654 * @deprecated This method does not support multiple connected networks
1655 * of the same type. Use {@link #getAllNetworks} and
1656 * {@link #getNetworkInfo(android.net.Network)} instead.
1657 */
1658 @Deprecated
1659 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1660 @NonNull
1661 public NetworkInfo[] getAllNetworkInfo() {
1662 try {
1663 return mService.getAllNetworkInfo();
1664 } catch (RemoteException e) {
1665 throw e.rethrowFromSystemServer();
1666 }
1667 }
1668
1669 /**
junyulaib1211372021-03-03 12:09:05 +08001670 * Return a list of {@link NetworkStateSnapshot}s, one for each network that is currently
1671 * connected.
1672 * @hide
1673 */
1674 @SystemApi(client = MODULE_LIBRARIES)
1675 @RequiresPermission(anyOf = {
1676 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1677 android.Manifest.permission.NETWORK_STACK,
1678 android.Manifest.permission.NETWORK_SETTINGS})
1679 @NonNull
Aaron Huangab615e52021-04-17 13:46:25 +08001680 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaib1211372021-03-03 12:09:05 +08001681 try {
Aaron Huangab615e52021-04-17 13:46:25 +08001682 return mService.getAllNetworkStateSnapshots();
junyulaib1211372021-03-03 12:09:05 +08001683 } catch (RemoteException e) {
1684 throw e.rethrowFromSystemServer();
1685 }
1686 }
1687
1688 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001689 * Returns the {@link Network} object currently serving a given type, or
1690 * null if the given type is not connected.
1691 *
1692 * @hide
1693 * @deprecated This method does not support multiple connected networks
1694 * of the same type. Use {@link #getAllNetworks} and
1695 * {@link #getNetworkInfo(android.net.Network)} instead.
1696 */
1697 @Deprecated
1698 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1699 @UnsupportedAppUsage
1700 public Network getNetworkForType(int networkType) {
1701 try {
1702 return mService.getNetworkForType(networkType);
1703 } catch (RemoteException e) {
1704 throw e.rethrowFromSystemServer();
1705 }
1706 }
1707
1708 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001709 * Returns an array of all {@link Network} currently tracked by the framework.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001710 *
Lorenzo Colitti86714b12021-05-17 20:31:21 +09001711 * @deprecated This method does not provide any notification of network state changes, forcing
1712 * apps to call it repeatedly. This is inefficient and prone to race conditions.
1713 * Apps should use methods such as
1714 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} instead.
1715 * Apps that desire to obtain information about networks that do not apply to them
1716 * can use {@link NetworkRequest.Builder#setIncludeOtherUidNetworks}.
1717 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001718 * @return an array of {@link Network} objects.
1719 */
1720 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1721 @NonNull
Lorenzo Colitti86714b12021-05-17 20:31:21 +09001722 @Deprecated
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001723 public Network[] getAllNetworks() {
1724 try {
1725 return mService.getAllNetworks();
1726 } catch (RemoteException e) {
1727 throw e.rethrowFromSystemServer();
1728 }
1729 }
1730
1731 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08001732 * Returns an array of {@link NetworkCapabilities} objects, representing
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001733 * the Networks that applications run by the given user will use by default.
1734 * @hide
1735 */
1736 @UnsupportedAppUsage
1737 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1738 try {
1739 return mService.getDefaultNetworkCapabilitiesForUser(
Roshan Piusa8a477b2020-12-17 14:53:09 -08001740 userId, mContext.getOpPackageName(), getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001741 } catch (RemoteException e) {
1742 throw e.rethrowFromSystemServer();
1743 }
1744 }
1745
1746 /**
1747 * Returns the IP information for the current default network.
1748 *
1749 * @return a {@link LinkProperties} object describing the IP info
1750 * for the current default network, or {@code null} if there
1751 * is no current default network.
1752 *
1753 * {@hide}
1754 * @deprecated please use {@link #getLinkProperties(Network)} on the return
1755 * value of {@link #getActiveNetwork()} instead. In particular,
1756 * this method will return non-null LinkProperties even if the
1757 * app is blocked by policy from using this network.
1758 */
1759 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1760 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 109783091)
1761 public LinkProperties getActiveLinkProperties() {
1762 try {
1763 return mService.getActiveLinkProperties();
1764 } catch (RemoteException e) {
1765 throw e.rethrowFromSystemServer();
1766 }
1767 }
1768
1769 /**
1770 * Returns the IP information for a given network type.
1771 *
1772 * @param networkType the network type of interest.
1773 * @return a {@link LinkProperties} object describing the IP info
1774 * for the given networkType, or {@code null} if there is
1775 * no current default network.
1776 *
1777 * {@hide}
1778 * @deprecated This method does not support multiple connected networks
1779 * of the same type. Use {@link #getAllNetworks},
1780 * {@link #getNetworkInfo(android.net.Network)}, and
1781 * {@link #getLinkProperties(android.net.Network)} instead.
1782 */
1783 @Deprecated
1784 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1785 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
1786 public LinkProperties getLinkProperties(int networkType) {
1787 try {
1788 return mService.getLinkPropertiesForType(networkType);
1789 } catch (RemoteException e) {
1790 throw e.rethrowFromSystemServer();
1791 }
1792 }
1793
1794 /**
1795 * Get the {@link LinkProperties} for the given {@link Network}. This
1796 * will return {@code null} if the network is unknown.
1797 *
1798 * @param network The {@link Network} object identifying the network in question.
1799 * @return The {@link LinkProperties} for the network, or {@code null}.
1800 */
1801 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1802 @Nullable
1803 public LinkProperties getLinkProperties(@Nullable Network network) {
1804 try {
1805 return mService.getLinkProperties(network);
1806 } catch (RemoteException e) {
1807 throw e.rethrowFromSystemServer();
1808 }
1809 }
1810
1811 /**
lucaslinc582d502022-01-27 09:07:00 +08001812 * Redact {@link LinkProperties} for a given package
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001813 *
lucaslinc582d502022-01-27 09:07:00 +08001814 * Returns an instance of the given {@link LinkProperties} appropriately redacted to send to the
1815 * given package, considering its permissions.
1816 *
1817 * @param lp A {@link LinkProperties} which will be redacted.
1818 * @param uid The target uid.
1819 * @param packageName The name of the package, for appops logging.
1820 * @return A redacted {@link LinkProperties} which is appropriate to send to the given uid,
1821 * or null if the uid lacks the ACCESS_NETWORK_STATE permission.
1822 * @hide
1823 */
1824 @RequiresPermission(anyOf = {
1825 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1826 android.Manifest.permission.NETWORK_STACK,
1827 android.Manifest.permission.NETWORK_SETTINGS})
1828 @SystemApi(client = MODULE_LIBRARIES)
1829 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08001830 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08001831 @NonNull String packageName) {
1832 try {
lucaslind2b06132022-03-02 10:56:57 +08001833 return mService.getRedactedLinkPropertiesForPackage(
lucaslinc582d502022-01-27 09:07:00 +08001834 lp, uid, packageName, getAttributionTag());
1835 } catch (RemoteException e) {
1836 throw e.rethrowFromSystemServer();
1837 }
1838 }
1839
1840 /**
1841 * Get the {@link NetworkCapabilities} for the given {@link Network}, or null.
1842 *
1843 * This will remove any location sensitive data in the returned {@link NetworkCapabilities}.
1844 * Some {@link TransportInfo} instances like {@link android.net.wifi.WifiInfo} contain location
1845 * sensitive information. To retrieve this location sensitive information (subject to
1846 * the caller's location permissions), use a {@link NetworkCallback} with the
1847 * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} flag instead.
1848 *
1849 * This method returns {@code null} if the network is unknown or if the |network| argument
1850 * is null.
Roshan Piuse08bc182020-12-22 15:10:42 -08001851 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001852 * @param network The {@link Network} object identifying the network in question.
Roshan Piuse08bc182020-12-22 15:10:42 -08001853 * @return The {@link NetworkCapabilities} for the network, or {@code null}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001854 */
1855 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
1856 @Nullable
1857 public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
1858 try {
Roshan Piusa8a477b2020-12-17 14:53:09 -08001859 return mService.getNetworkCapabilities(
1860 network, mContext.getOpPackageName(), getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001861 } catch (RemoteException e) {
1862 throw e.rethrowFromSystemServer();
1863 }
1864 }
1865
1866 /**
lucaslinc582d502022-01-27 09:07:00 +08001867 * Redact {@link NetworkCapabilities} for a given package.
1868 *
1869 * Returns an instance of {@link NetworkCapabilities} that is appropriately redacted to send
lucaslind2b06132022-03-02 10:56:57 +08001870 * to the given package, considering its permissions. If the passed capabilities contain
1871 * location-sensitive information, they will be redacted to the correct degree for the location
1872 * permissions of the app (COARSE or FINE), and will blame the UID accordingly for retrieving
1873 * that level of location. If the UID holds no location permission, the returned object will
1874 * contain no location-sensitive information and the UID is not blamed.
lucaslinc582d502022-01-27 09:07:00 +08001875 *
1876 * @param nc A {@link NetworkCapabilities} instance which will be redacted.
1877 * @param uid The target uid.
1878 * @param packageName The name of the package, for appops logging.
1879 * @return A redacted {@link NetworkCapabilities} which is appropriate to send to the given uid,
1880 * or null if the uid lacks the ACCESS_NETWORK_STATE permission.
1881 * @hide
1882 */
1883 @RequiresPermission(anyOf = {
1884 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
1885 android.Manifest.permission.NETWORK_STACK,
1886 android.Manifest.permission.NETWORK_SETTINGS})
1887 @SystemApi(client = MODULE_LIBRARIES)
1888 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08001889 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
lucaslinc582d502022-01-27 09:07:00 +08001890 @NonNull NetworkCapabilities nc,
1891 int uid, @NonNull String packageName) {
1892 try {
lucaslind2b06132022-03-02 10:56:57 +08001893 return mService.getRedactedNetworkCapabilitiesForPackage(nc, uid, packageName,
lucaslinc582d502022-01-27 09:07:00 +08001894 getAttributionTag());
1895 } catch (RemoteException e) {
1896 throw e.rethrowFromSystemServer();
1897 }
1898 }
1899
1900 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001901 * Gets a URL that can be used for resolving whether a captive portal is present.
1902 * 1. This URL should respond with a 204 response to a GET request to indicate no captive
1903 * portal is present.
1904 * 2. This URL must be HTTP as redirect responses are used to find captive portal
1905 * sign-in pages. Captive portals cannot respond to HTTPS requests with redirects.
1906 *
1907 * The system network validation may be using different strategies to detect captive portals,
1908 * so this method does not necessarily return a URL used by the system. It only returns a URL
1909 * that may be relevant for other components trying to detect captive portals.
1910 *
1911 * @hide
Chalard Jean0c7ebe92022-08-03 14:45:47 +09001912 * @deprecated This API returns a URL which is not guaranteed to be one of the URLs used by the
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09001913 * system.
1914 */
1915 @Deprecated
1916 @SystemApi
1917 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
1918 public String getCaptivePortalServerUrl() {
1919 try {
1920 return mService.getCaptivePortalServerUrl();
1921 } catch (RemoteException e) {
1922 throw e.rethrowFromSystemServer();
1923 }
1924 }
1925
1926 /**
1927 * Tells the underlying networking system that the caller wants to
1928 * begin using the named feature. The interpretation of {@code feature}
1929 * is completely up to each networking implementation.
1930 *
1931 * <p>This method requires the caller to hold either the
1932 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1933 * or the ability to modify system settings as determined by
1934 * {@link android.provider.Settings.System#canWrite}.</p>
1935 *
1936 * @param networkType specifies which network the request pertains to
1937 * @param feature the name of the feature to be used
1938 * @return an integer value representing the outcome of the request.
1939 * The interpretation of this value is specific to each networking
1940 * implementation+feature combination, except that the value {@code -1}
1941 * always indicates failure.
1942 *
1943 * @deprecated Deprecated in favor of the cleaner
1944 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
1945 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
1946 * throw {@code UnsupportedOperationException} if called.
1947 * @removed
1948 */
1949 @Deprecated
1950 public int startUsingNetworkFeature(int networkType, String feature) {
1951 checkLegacyRoutingApiAccess();
1952 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
1953 if (netCap == null) {
1954 Log.d(TAG, "Can't satisfy startUsingNetworkFeature for " + networkType + ", " +
1955 feature);
1956 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
1957 }
1958
1959 NetworkRequest request = null;
1960 synchronized (sLegacyRequests) {
1961 LegacyRequest l = sLegacyRequests.get(netCap);
1962 if (l != null) {
1963 Log.d(TAG, "renewing startUsingNetworkFeature request " + l.networkRequest);
1964 renewRequestLocked(l);
1965 if (l.currentNetwork != null) {
1966 return DEPRECATED_PHONE_CONSTANT_APN_ALREADY_ACTIVE;
1967 } else {
1968 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
1969 }
1970 }
1971
1972 request = requestNetworkForFeatureLocked(netCap);
1973 }
1974 if (request != null) {
1975 Log.d(TAG, "starting startUsingNetworkFeature for request " + request);
1976 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_STARTED;
1977 } else {
1978 Log.d(TAG, " request Failed");
1979 return DEPRECATED_PHONE_CONSTANT_APN_REQUEST_FAILED;
1980 }
1981 }
1982
1983 /**
1984 * Tells the underlying networking system that the caller is finished
1985 * using the named feature. The interpretation of {@code feature}
1986 * is completely up to each networking implementation.
1987 *
1988 * <p>This method requires the caller to hold either the
1989 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
1990 * or the ability to modify system settings as determined by
1991 * {@link android.provider.Settings.System#canWrite}.</p>
1992 *
1993 * @param networkType specifies which network the request pertains to
1994 * @param feature the name of the feature that is no longer needed
1995 * @return an integer value representing the outcome of the request.
1996 * The interpretation of this value is specific to each networking
1997 * implementation+feature combination, except that the value {@code -1}
1998 * always indicates failure.
1999 *
2000 * @deprecated Deprecated in favor of the cleaner
2001 * {@link #unregisterNetworkCallback(NetworkCallback)} API.
2002 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
2003 * throw {@code UnsupportedOperationException} if called.
2004 * @removed
2005 */
2006 @Deprecated
2007 public int stopUsingNetworkFeature(int networkType, String feature) {
2008 checkLegacyRoutingApiAccess();
2009 NetworkCapabilities netCap = networkCapabilitiesForFeature(networkType, feature);
2010 if (netCap == null) {
2011 Log.d(TAG, "Can't satisfy stopUsingNetworkFeature for " + networkType + ", " +
2012 feature);
2013 return -1;
2014 }
2015
2016 if (removeRequestForFeature(netCap)) {
2017 Log.d(TAG, "stopUsingNetworkFeature for " + networkType + ", " + feature);
2018 }
2019 return 1;
2020 }
2021
2022 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2023 private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
2024 if (networkType == TYPE_MOBILE) {
2025 switch (feature) {
2026 case "enableCBS":
2027 return networkCapabilitiesForType(TYPE_MOBILE_CBS);
2028 case "enableDUN":
2029 case "enableDUNAlways":
2030 return networkCapabilitiesForType(TYPE_MOBILE_DUN);
2031 case "enableFOTA":
2032 return networkCapabilitiesForType(TYPE_MOBILE_FOTA);
2033 case "enableHIPRI":
2034 return networkCapabilitiesForType(TYPE_MOBILE_HIPRI);
2035 case "enableIMS":
2036 return networkCapabilitiesForType(TYPE_MOBILE_IMS);
2037 case "enableMMS":
2038 return networkCapabilitiesForType(TYPE_MOBILE_MMS);
2039 case "enableSUPL":
2040 return networkCapabilitiesForType(TYPE_MOBILE_SUPL);
2041 default:
2042 return null;
2043 }
2044 } else if (networkType == TYPE_WIFI && "p2p".equals(feature)) {
2045 return networkCapabilitiesForType(TYPE_WIFI_P2P);
2046 }
2047 return null;
2048 }
2049
2050 private int legacyTypeForNetworkCapabilities(NetworkCapabilities netCap) {
2051 if (netCap == null) return TYPE_NONE;
2052 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
2053 return TYPE_MOBILE_CBS;
2054 }
2055 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS)) {
2056 return TYPE_MOBILE_IMS;
2057 }
2058 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOTA)) {
2059 return TYPE_MOBILE_FOTA;
2060 }
2061 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_DUN)) {
2062 return TYPE_MOBILE_DUN;
2063 }
2064 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_SUPL)) {
2065 return TYPE_MOBILE_SUPL;
2066 }
2067 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_MMS)) {
2068 return TYPE_MOBILE_MMS;
2069 }
2070 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
2071 return TYPE_MOBILE_HIPRI;
2072 }
2073 if (netCap.hasCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P)) {
2074 return TYPE_WIFI_P2P;
2075 }
2076 return TYPE_NONE;
2077 }
2078
2079 private static class LegacyRequest {
2080 NetworkCapabilities networkCapabilities;
2081 NetworkRequest networkRequest;
2082 int expireSequenceNumber;
2083 Network currentNetwork;
2084 int delay = -1;
2085
2086 private void clearDnsBinding() {
2087 if (currentNetwork != null) {
2088 currentNetwork = null;
2089 setProcessDefaultNetworkForHostResolution(null);
2090 }
2091 }
2092
2093 NetworkCallback networkCallback = new NetworkCallback() {
2094 @Override
2095 public void onAvailable(Network network) {
2096 currentNetwork = network;
2097 Log.d(TAG, "startUsingNetworkFeature got Network:" + network);
2098 setProcessDefaultNetworkForHostResolution(network);
2099 }
2100 @Override
2101 public void onLost(Network network) {
2102 if (network.equals(currentNetwork)) clearDnsBinding();
2103 Log.d(TAG, "startUsingNetworkFeature lost Network:" + network);
2104 }
2105 };
2106 }
2107
2108 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2109 private static final HashMap<NetworkCapabilities, LegacyRequest> sLegacyRequests =
2110 new HashMap<>();
2111
2112 private NetworkRequest findRequestForFeature(NetworkCapabilities netCap) {
2113 synchronized (sLegacyRequests) {
2114 LegacyRequest l = sLegacyRequests.get(netCap);
2115 if (l != null) return l.networkRequest;
2116 }
2117 return null;
2118 }
2119
2120 private void renewRequestLocked(LegacyRequest l) {
2121 l.expireSequenceNumber++;
2122 Log.d(TAG, "renewing request to seqNum " + l.expireSequenceNumber);
2123 sendExpireMsgForFeature(l.networkCapabilities, l.expireSequenceNumber, l.delay);
2124 }
2125
2126 private void expireRequest(NetworkCapabilities netCap, int sequenceNum) {
2127 int ourSeqNum = -1;
2128 synchronized (sLegacyRequests) {
2129 LegacyRequest l = sLegacyRequests.get(netCap);
2130 if (l == null) return;
2131 ourSeqNum = l.expireSequenceNumber;
2132 if (l.expireSequenceNumber == sequenceNum) removeRequestForFeature(netCap);
2133 }
2134 Log.d(TAG, "expireRequest with " + ourSeqNum + ", " + sequenceNum);
2135 }
2136
2137 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2138 private NetworkRequest requestNetworkForFeatureLocked(NetworkCapabilities netCap) {
2139 int delay = -1;
2140 int type = legacyTypeForNetworkCapabilities(netCap);
2141 try {
2142 delay = mService.getRestoreDefaultNetworkDelay(type);
2143 } catch (RemoteException e) {
2144 throw e.rethrowFromSystemServer();
2145 }
2146 LegacyRequest l = new LegacyRequest();
2147 l.networkCapabilities = netCap;
2148 l.delay = delay;
2149 l.expireSequenceNumber = 0;
2150 l.networkRequest = sendRequestForNetwork(
2151 netCap, l.networkCallback, 0, REQUEST, type, getDefaultHandler());
2152 if (l.networkRequest == null) return null;
2153 sLegacyRequests.put(netCap, l);
2154 sendExpireMsgForFeature(netCap, l.expireSequenceNumber, delay);
2155 return l.networkRequest;
2156 }
2157
2158 private void sendExpireMsgForFeature(NetworkCapabilities netCap, int seqNum, int delay) {
2159 if (delay >= 0) {
2160 Log.d(TAG, "sending expire msg with seqNum " + seqNum + " and delay " + delay);
2161 CallbackHandler handler = getDefaultHandler();
2162 Message msg = handler.obtainMessage(EXPIRE_LEGACY_REQUEST, seqNum, 0, netCap);
2163 handler.sendMessageDelayed(msg, delay);
2164 }
2165 }
2166
2167 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2168 private boolean removeRequestForFeature(NetworkCapabilities netCap) {
2169 final LegacyRequest l;
2170 synchronized (sLegacyRequests) {
2171 l = sLegacyRequests.remove(netCap);
2172 }
2173 if (l == null) return false;
2174 unregisterNetworkCallback(l.networkCallback);
2175 l.clearDnsBinding();
2176 return true;
2177 }
2178
2179 private static final SparseIntArray sLegacyTypeToTransport = new SparseIntArray();
2180 static {
2181 sLegacyTypeToTransport.put(TYPE_MOBILE, NetworkCapabilities.TRANSPORT_CELLULAR);
2182 sLegacyTypeToTransport.put(TYPE_MOBILE_CBS, NetworkCapabilities.TRANSPORT_CELLULAR);
2183 sLegacyTypeToTransport.put(TYPE_MOBILE_DUN, NetworkCapabilities.TRANSPORT_CELLULAR);
2184 sLegacyTypeToTransport.put(TYPE_MOBILE_FOTA, NetworkCapabilities.TRANSPORT_CELLULAR);
2185 sLegacyTypeToTransport.put(TYPE_MOBILE_HIPRI, NetworkCapabilities.TRANSPORT_CELLULAR);
2186 sLegacyTypeToTransport.put(TYPE_MOBILE_IMS, NetworkCapabilities.TRANSPORT_CELLULAR);
2187 sLegacyTypeToTransport.put(TYPE_MOBILE_MMS, NetworkCapabilities.TRANSPORT_CELLULAR);
2188 sLegacyTypeToTransport.put(TYPE_MOBILE_SUPL, NetworkCapabilities.TRANSPORT_CELLULAR);
2189 sLegacyTypeToTransport.put(TYPE_WIFI, NetworkCapabilities.TRANSPORT_WIFI);
2190 sLegacyTypeToTransport.put(TYPE_WIFI_P2P, NetworkCapabilities.TRANSPORT_WIFI);
2191 sLegacyTypeToTransport.put(TYPE_BLUETOOTH, NetworkCapabilities.TRANSPORT_BLUETOOTH);
2192 sLegacyTypeToTransport.put(TYPE_ETHERNET, NetworkCapabilities.TRANSPORT_ETHERNET);
2193 }
2194
2195 private static final SparseIntArray sLegacyTypeToCapability = new SparseIntArray();
2196 static {
2197 sLegacyTypeToCapability.put(TYPE_MOBILE_CBS, NetworkCapabilities.NET_CAPABILITY_CBS);
2198 sLegacyTypeToCapability.put(TYPE_MOBILE_DUN, NetworkCapabilities.NET_CAPABILITY_DUN);
2199 sLegacyTypeToCapability.put(TYPE_MOBILE_FOTA, NetworkCapabilities.NET_CAPABILITY_FOTA);
2200 sLegacyTypeToCapability.put(TYPE_MOBILE_IMS, NetworkCapabilities.NET_CAPABILITY_IMS);
2201 sLegacyTypeToCapability.put(TYPE_MOBILE_MMS, NetworkCapabilities.NET_CAPABILITY_MMS);
2202 sLegacyTypeToCapability.put(TYPE_MOBILE_SUPL, NetworkCapabilities.NET_CAPABILITY_SUPL);
2203 sLegacyTypeToCapability.put(TYPE_WIFI_P2P, NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
2204 }
2205
2206 /**
2207 * Given a legacy type (TYPE_WIFI, ...) returns a NetworkCapabilities
2208 * instance suitable for registering a request or callback. Throws an
2209 * IllegalArgumentException if no mapping from the legacy type to
2210 * NetworkCapabilities is known.
2211 *
2212 * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
2213 * to find the network instead.
2214 * @hide
2215 */
2216 public static NetworkCapabilities networkCapabilitiesForType(int type) {
2217 final NetworkCapabilities nc = new NetworkCapabilities();
2218
2219 // Map from type to transports.
2220 final int NOT_FOUND = -1;
2221 final int transport = sLegacyTypeToTransport.get(type, NOT_FOUND);
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002222 if (transport == NOT_FOUND) {
2223 throw new IllegalArgumentException("unknown legacy type: " + type);
2224 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002225 nc.addTransportType(transport);
2226
2227 // Map from type to capabilities.
2228 nc.addCapability(sLegacyTypeToCapability.get(
2229 type, NetworkCapabilities.NET_CAPABILITY_INTERNET));
2230 nc.maybeMarkCapabilitiesRestricted();
2231 return nc;
2232 }
2233
2234 /** @hide */
2235 public static class PacketKeepaliveCallback {
2236 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2237 public PacketKeepaliveCallback() {
2238 }
2239 /** The requested keepalive was successfully started. */
2240 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2241 public void onStarted() {}
Chalard Jeanbdb82822023-01-19 23:14:02 +09002242 /** The keepalive was resumed after being paused by the system. */
2243 public void onResumed() {}
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002244 /** The keepalive was successfully stopped. */
2245 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2246 public void onStopped() {}
Chalard Jeanbdb82822023-01-19 23:14:02 +09002247 /** The keepalive was paused automatically by the system. */
2248 public void onPaused() {}
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002249 /** An error occurred. */
2250 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2251 public void onError(int error) {}
2252 }
2253
2254 /**
2255 * Allows applications to request that the system periodically send specific packets on their
2256 * behalf, using hardware offload to save battery power.
2257 *
2258 * To request that the system send keepalives, call one of the methods that return a
2259 * {@link ConnectivityManager.PacketKeepalive} object, such as {@link #startNattKeepalive},
2260 * passing in a non-null callback. If the callback is successfully started, the callback's
2261 * {@code onStarted} method will be called. If an error occurs, {@code onError} will be called,
2262 * specifying one of the {@code ERROR_*} constants in this class.
2263 *
2264 * To stop an existing keepalive, call {@link PacketKeepalive#stop}. The system will call
2265 * {@link PacketKeepaliveCallback#onStopped} if the operation was successful or
2266 * {@link PacketKeepaliveCallback#onError} if an error occurred.
2267 *
2268 * @deprecated Use {@link SocketKeepalive} instead.
2269 *
2270 * @hide
2271 */
2272 public class PacketKeepalive {
2273
2274 private static final String TAG = "PacketKeepalive";
2275
2276 /** @hide */
2277 public static final int SUCCESS = 0;
2278
2279 /** @hide */
2280 public static final int NO_KEEPALIVE = -1;
2281
2282 /** @hide */
2283 public static final int BINDER_DIED = -10;
2284
2285 /** The specified {@code Network} is not connected. */
2286 public static final int ERROR_INVALID_NETWORK = -20;
2287 /** The specified IP addresses are invalid. For example, the specified source IP address is
2288 * not configured on the specified {@code Network}. */
2289 public static final int ERROR_INVALID_IP_ADDRESS = -21;
2290 /** The requested port is invalid. */
2291 public static final int ERROR_INVALID_PORT = -22;
2292 /** The packet length is invalid (e.g., too long). */
2293 public static final int ERROR_INVALID_LENGTH = -23;
2294 /** The packet transmission interval is invalid (e.g., too short). */
2295 public static final int ERROR_INVALID_INTERVAL = -24;
2296
2297 /** The hardware does not support this request. */
2298 public static final int ERROR_HARDWARE_UNSUPPORTED = -30;
2299 /** The hardware returned an error. */
2300 public static final int ERROR_HARDWARE_ERROR = -31;
2301
2302 /** The NAT-T destination port for IPsec */
2303 public static final int NATT_PORT = 4500;
2304
2305 /** The minimum interval in seconds between keepalive packet transmissions */
2306 public static final int MIN_INTERVAL = 10;
2307
2308 private final Network mNetwork;
2309 private final ISocketKeepaliveCallback mCallback;
2310 private final ExecutorService mExecutor;
2311
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002312 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2313 public void stop() {
2314 try {
2315 mExecutor.execute(() -> {
2316 try {
Chalard Jeanf0b261e2023-02-03 22:11:20 +09002317 mService.stopKeepalive(mCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002318 } catch (RemoteException e) {
2319 Log.e(TAG, "Error stopping packet keepalive: ", e);
2320 throw e.rethrowFromSystemServer();
2321 }
2322 });
2323 } catch (RejectedExecutionException e) {
2324 // The internal executor has already stopped due to previous event.
2325 }
2326 }
2327
2328 private PacketKeepalive(Network network, PacketKeepaliveCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002329 Objects.requireNonNull(network, "network cannot be null");
2330 Objects.requireNonNull(callback, "callback cannot be null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002331 mNetwork = network;
2332 mExecutor = Executors.newSingleThreadExecutor();
2333 mCallback = new ISocketKeepaliveCallback.Stub() {
2334 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +09002335 public void onStarted() {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002336 final long token = Binder.clearCallingIdentity();
2337 try {
2338 mExecutor.execute(() -> {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002339 callback.onStarted();
2340 });
2341 } finally {
2342 Binder.restoreCallingIdentity(token);
2343 }
2344 }
2345
2346 @Override
Chalard Jeanbdb82822023-01-19 23:14:02 +09002347 public void onResumed() {
2348 final long token = Binder.clearCallingIdentity();
2349 try {
2350 mExecutor.execute(() -> {
2351 callback.onResumed();
2352 });
2353 } finally {
2354 Binder.restoreCallingIdentity(token);
2355 }
2356 }
2357
2358 @Override
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002359 public void onStopped() {
2360 final long token = Binder.clearCallingIdentity();
2361 try {
2362 mExecutor.execute(() -> {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002363 callback.onStopped();
2364 });
2365 } finally {
2366 Binder.restoreCallingIdentity(token);
2367 }
2368 mExecutor.shutdown();
2369 }
2370
2371 @Override
Chalard Jeanbdb82822023-01-19 23:14:02 +09002372 public void onPaused() {
2373 final long token = Binder.clearCallingIdentity();
2374 try {
2375 mExecutor.execute(() -> {
2376 callback.onPaused();
2377 });
2378 } finally {
2379 Binder.restoreCallingIdentity(token);
2380 }
2381 mExecutor.shutdown();
2382 }
2383
2384 @Override
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002385 public void onError(int error) {
2386 final long token = Binder.clearCallingIdentity();
2387 try {
2388 mExecutor.execute(() -> {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002389 callback.onError(error);
2390 });
2391 } finally {
2392 Binder.restoreCallingIdentity(token);
2393 }
2394 mExecutor.shutdown();
2395 }
2396
2397 @Override
2398 public void onDataReceived() {
2399 // PacketKeepalive is only used for Nat-T keepalive and as such does not invoke
2400 // this callback when data is received.
2401 }
2402 };
2403 }
2404 }
2405
2406 /**
2407 * Starts an IPsec NAT-T keepalive packet with the specified parameters.
2408 *
2409 * @deprecated Use {@link #createSocketKeepalive} instead.
2410 *
2411 * @hide
2412 */
2413 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2414 public PacketKeepalive startNattKeepalive(
2415 Network network, int intervalSeconds, PacketKeepaliveCallback callback,
2416 InetAddress srcAddr, int srcPort, InetAddress dstAddr) {
2417 final PacketKeepalive k = new PacketKeepalive(network, callback);
2418 try {
2419 mService.startNattKeepalive(network, intervalSeconds, k.mCallback,
2420 srcAddr.getHostAddress(), srcPort, dstAddr.getHostAddress());
2421 } catch (RemoteException e) {
2422 Log.e(TAG, "Error starting packet keepalive: ", e);
2423 throw e.rethrowFromSystemServer();
2424 }
2425 return k;
2426 }
2427
2428 // Construct an invalid fd.
2429 private ParcelFileDescriptor createInvalidFd() {
2430 final int invalidFd = -1;
2431 return ParcelFileDescriptor.adoptFd(invalidFd);
2432 }
2433
2434 /**
2435 * Request that keepalives be started on a IPsec NAT-T socket.
2436 *
2437 * @param network The {@link Network} the socket is on.
2438 * @param socket The socket that needs to be kept alive.
2439 * @param source The source address of the {@link UdpEncapsulationSocket}.
2440 * @param destination The destination address of the {@link UdpEncapsulationSocket}.
2441 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2442 * must run callback sequentially, otherwise the order of callbacks cannot be
2443 * guaranteed.
2444 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2445 * changes. Must be extended by applications that use this API.
2446 *
2447 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2448 * given socket.
2449 **/
2450 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
2451 @NonNull UdpEncapsulationSocket socket,
2452 @NonNull InetAddress source,
2453 @NonNull InetAddress destination,
2454 @NonNull @CallbackExecutor Executor executor,
2455 @NonNull Callback callback) {
2456 ParcelFileDescriptor dup;
2457 try {
2458 // Dup is needed here as the pfd inside the socket is owned by the IpSecService,
2459 // which cannot be obtained by the app process.
2460 dup = ParcelFileDescriptor.dup(socket.getFileDescriptor());
2461 } catch (IOException ignored) {
2462 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2463 // ERROR_INVALID_SOCKET.
2464 dup = createInvalidFd();
2465 }
2466 return new NattSocketKeepalive(mService, network, dup, socket.getResourceId(), source,
2467 destination, executor, callback);
2468 }
2469
2470 /**
2471 * Request that keepalives be started on a IPsec NAT-T socket file descriptor. Directly called
2472 * by system apps which don't use IpSecService to create {@link UdpEncapsulationSocket}.
2473 *
2474 * @param network The {@link Network} the socket is on.
2475 * @param pfd The {@link ParcelFileDescriptor} that needs to be kept alive. The provided
2476 * {@link ParcelFileDescriptor} must be bound to a port and the keepalives will be sent
2477 * from that port.
2478 * @param source The source address of the {@link UdpEncapsulationSocket}.
2479 * @param destination The destination address of the {@link UdpEncapsulationSocket}. The
2480 * keepalive packets will always be sent to port 4500 of the given {@code destination}.
2481 * @param executor The executor on which callback will be invoked. The provided {@link Executor}
2482 * must run callback sequentially, otherwise the order of callbacks cannot be
2483 * guaranteed.
2484 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2485 * changes. Must be extended by applications that use this API.
2486 *
2487 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2488 * given socket.
2489 * @hide
2490 */
2491 @SystemApi
2492 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
2493 public @NonNull SocketKeepalive createNattKeepalive(@NonNull Network network,
2494 @NonNull ParcelFileDescriptor pfd,
2495 @NonNull InetAddress source,
2496 @NonNull InetAddress destination,
2497 @NonNull @CallbackExecutor Executor executor,
2498 @NonNull Callback callback) {
2499 ParcelFileDescriptor dup;
2500 try {
2501 // TODO: Consider remove unnecessary dup.
2502 dup = pfd.dup();
2503 } catch (IOException ignored) {
2504 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2505 // ERROR_INVALID_SOCKET.
2506 dup = createInvalidFd();
2507 }
2508 return new NattSocketKeepalive(mService, network, dup,
Remi NGUYEN VANa29be5c2021-03-11 10:56:49 +00002509 -1 /* Unused */, source, destination, executor, callback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002510 }
2511
2512 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09002513 * Request that keepalives be started on a TCP socket. The socket must be established.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002514 *
2515 * @param network The {@link Network} the socket is on.
2516 * @param socket The socket that needs to be kept alive.
2517 * @param executor The executor on which callback will be invoked. This implementation assumes
2518 * the provided {@link Executor} runs the callbacks in sequence with no
2519 * concurrency. Failing this, no guarantee of correctness can be made. It is
2520 * the responsibility of the caller to ensure the executor provides this
2521 * guarantee. A simple way of creating such an executor is with the standard
2522 * tool {@code Executors.newSingleThreadExecutor}.
2523 * @param callback A {@link SocketKeepalive.Callback}. Used for notifications about keepalive
2524 * changes. Must be extended by applications that use this API.
2525 *
2526 * @return A {@link SocketKeepalive} object that can be used to control the keepalive on the
2527 * given socket.
2528 * @hide
2529 */
2530 @SystemApi
2531 @RequiresPermission(android.Manifest.permission.PACKET_KEEPALIVE_OFFLOAD)
2532 public @NonNull SocketKeepalive createSocketKeepalive(@NonNull Network network,
2533 @NonNull Socket socket,
Sherri Lin443b7182023-02-08 04:49:29 +01002534 @NonNull @CallbackExecutor Executor executor,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002535 @NonNull Callback callback) {
2536 ParcelFileDescriptor dup;
2537 try {
2538 dup = ParcelFileDescriptor.fromSocket(socket);
2539 } catch (UncheckedIOException ignored) {
2540 // Construct an invalid fd, so that if the user later calls start(), it will fail with
2541 // ERROR_INVALID_SOCKET.
2542 dup = createInvalidFd();
2543 }
2544 return new TcpSocketKeepalive(mService, network, dup, executor, callback);
2545 }
2546
2547 /**
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +09002548 * Get the supported keepalive count for each transport configured in resource overlays.
2549 *
2550 * @return An array of supported keepalive count for each transport type.
2551 * @hide
2552 */
2553 @RequiresPermission(anyOf = { android.Manifest.permission.NETWORK_SETTINGS,
2554 // CTS 13 used QUERY_ALL_PACKAGES to get the resource value, which was implemented
2555 // as below in KeepaliveUtils. Also allow that permission so that KeepaliveUtils can
2556 // use this method and avoid breaking released CTS. Apps that have this permission
2557 // can query the resource themselves anyway.
2558 android.Manifest.permission.QUERY_ALL_PACKAGES })
2559 public int[] getSupportedKeepalives() {
2560 try {
2561 return mService.getSupportedKeepalives();
2562 } catch (RemoteException e) {
2563 throw e.rethrowFromSystemServer();
2564 }
2565 }
2566
2567 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002568 * Ensure that a network route exists to deliver traffic to the specified
2569 * host via the specified network interface. An attempt to add a route that
2570 * already exists is ignored, but treated as successful.
2571 *
2572 * <p>This method requires the caller to hold either the
2573 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2574 * or the ability to modify system settings as determined by
2575 * {@link android.provider.Settings.System#canWrite}.</p>
2576 *
2577 * @param networkType the type of the network over which traffic to the specified
2578 * host is to be routed
2579 * @param hostAddress the IP address of the host to which the route is desired
2580 * @return {@code true} on success, {@code false} on failure
2581 *
2582 * @deprecated Deprecated in favor of the
2583 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
2584 * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
2585 * In {@link VERSION_CODES#M}, and above, this method is unsupported and will
2586 * throw {@code UnsupportedOperationException} if called.
2587 * @removed
2588 */
2589 @Deprecated
2590 public boolean requestRouteToHost(int networkType, int hostAddress) {
2591 return requestRouteToHostAddress(networkType, NetworkUtils.intToInetAddress(hostAddress));
2592 }
2593
2594 /**
2595 * Ensure that a network route exists to deliver traffic to the specified
2596 * host via the specified network interface. An attempt to add a route that
2597 * already exists is ignored, but treated as successful.
2598 *
2599 * <p>This method requires the caller to hold either the
2600 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2601 * or the ability to modify system settings as determined by
2602 * {@link android.provider.Settings.System#canWrite}.</p>
2603 *
2604 * @param networkType the type of the network over which traffic to the specified
2605 * host is to be routed
2606 * @param hostAddress the IP address of the host to which the route is desired
2607 * @return {@code true} on success, {@code false} on failure
2608 * @hide
2609 * @deprecated Deprecated in favor of the {@link #requestNetwork} and
2610 * {@link #bindProcessToNetwork} API.
2611 */
2612 @Deprecated
2613 @UnsupportedAppUsage
lucaslin97fb10a2021-03-22 11:51:27 +08002614 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002615 public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
2616 checkLegacyRoutingApiAccess();
2617 try {
2618 return mService.requestRouteToHostAddress(networkType, hostAddress.getAddress(),
2619 mContext.getOpPackageName(), getAttributionTag());
2620 } catch (RemoteException e) {
2621 throw e.rethrowFromSystemServer();
2622 }
2623 }
2624
2625 /**
2626 * @return the context's attribution tag
2627 */
2628 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2629 private @Nullable String getAttributionTag() {
Remi NGUYEN VANa522fc22021-02-01 10:25:24 +00002630 return mContext.getAttributionTag();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002631 }
2632
2633 /**
2634 * Returns the value of the setting for background data usage. If false,
2635 * applications should not use the network if the application is not in the
2636 * foreground. Developers should respect this setting, and check the value
2637 * of this before performing any background data operations.
2638 * <p>
2639 * All applications that have background services that use the network
2640 * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}.
2641 * <p>
2642 * @deprecated As of {@link VERSION_CODES#ICE_CREAM_SANDWICH}, availability of
2643 * background data depends on several combined factors, and this method will
2644 * always return {@code true}. Instead, when background data is unavailable,
2645 * {@link #getActiveNetworkInfo()} will now appear disconnected.
2646 *
2647 * @return Whether background data usage is allowed.
2648 */
2649 @Deprecated
2650 public boolean getBackgroundDataSetting() {
2651 // assume that background data is allowed; final authority is
2652 // NetworkInfo which may be blocked.
2653 return true;
2654 }
2655
2656 /**
2657 * Sets the value of the setting for background data usage.
2658 *
2659 * @param allowBackgroundData Whether an application should use data while
2660 * it is in the background.
2661 *
2662 * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING
2663 * @see #getBackgroundDataSetting()
2664 * @hide
2665 */
2666 @Deprecated
2667 @UnsupportedAppUsage
2668 public void setBackgroundDataSetting(boolean allowBackgroundData) {
2669 // ignored
2670 }
2671
2672 /**
2673 * @hide
2674 * @deprecated Talk to TelephonyManager directly
2675 */
2676 @Deprecated
2677 @UnsupportedAppUsage
2678 public boolean getMobileDataEnabled() {
2679 TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2680 if (tm != null) {
2681 int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2682 Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2683 boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2684 Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2685 + " retVal=" + retVal);
2686 return retVal;
2687 }
2688 Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
2689 return false;
2690 }
2691
2692 /**
2693 * Callback for use with {@link ConnectivityManager#addDefaultNetworkActiveListener}
2694 * to find out when the system default network has gone in to a high power state.
2695 */
2696 public interface OnNetworkActiveListener {
2697 /**
2698 * Called on the main thread of the process to report that the current data network
2699 * has become active, and it is now a good time to perform any pending network
2700 * operations. Note that this listener only tells you when the network becomes
2701 * active; if at any other time you want to know whether it is active (and thus okay
2702 * to initiate network traffic), you can retrieve its instantaneous state with
2703 * {@link ConnectivityManager#isDefaultNetworkActive}.
2704 */
2705 void onNetworkActive();
2706 }
2707
Chiachang Wang2de41682021-09-23 10:46:03 +08002708 @GuardedBy("mNetworkActivityListeners")
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002709 private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
2710 mNetworkActivityListeners = new ArrayMap<>();
2711
2712 /**
2713 * Start listening to reports when the system's default data network is active, meaning it is
2714 * a good time to perform network traffic. Use {@link #isDefaultNetworkActive()}
2715 * to determine the current state of the system's default network after registering the
2716 * listener.
2717 * <p>
2718 * If the process default network has been set with
2719 * {@link ConnectivityManager#bindProcessToNetwork} this function will not
2720 * reflect the process's default, but the system default.
2721 *
2722 * @param l The listener to be told when the network is active.
2723 */
2724 public void addDefaultNetworkActiveListener(final OnNetworkActiveListener l) {
Chiachang Wang2de41682021-09-23 10:46:03 +08002725 final INetworkActivityListener rl = new INetworkActivityListener.Stub() {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002726 @Override
2727 public void onNetworkActive() throws RemoteException {
2728 l.onNetworkActive();
2729 }
2730 };
2731
Chiachang Wang2de41682021-09-23 10:46:03 +08002732 synchronized (mNetworkActivityListeners) {
2733 try {
2734 mService.registerNetworkActivityListener(rl);
2735 mNetworkActivityListeners.put(l, rl);
2736 } catch (RemoteException e) {
2737 throw e.rethrowFromSystemServer();
2738 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002739 }
2740 }
2741
2742 /**
2743 * Remove network active listener previously registered with
2744 * {@link #addDefaultNetworkActiveListener}.
2745 *
2746 * @param l Previously registered listener.
2747 */
2748 public void removeDefaultNetworkActiveListener(@NonNull OnNetworkActiveListener l) {
Chiachang Wang2de41682021-09-23 10:46:03 +08002749 synchronized (mNetworkActivityListeners) {
2750 final INetworkActivityListener rl = mNetworkActivityListeners.get(l);
2751 if (rl == null) {
2752 throw new IllegalArgumentException("Listener was not registered.");
2753 }
2754 try {
2755 mService.unregisterNetworkActivityListener(rl);
2756 mNetworkActivityListeners.remove(l);
2757 } catch (RemoteException e) {
2758 throw e.rethrowFromSystemServer();
2759 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002760 }
2761 }
2762
2763 /**
2764 * Return whether the data network is currently active. An active network means that
2765 * it is currently in a high power state for performing data transmission. On some
2766 * types of networks, it may be expensive to move and stay in such a state, so it is
2767 * more power efficient to batch network traffic together when the radio is already in
2768 * this state. This method tells you whether right now is currently a good time to
2769 * initiate network traffic, as the network is already active.
2770 */
2771 public boolean isDefaultNetworkActive() {
2772 try {
lucaslin709eb842021-01-21 02:04:15 +08002773 return mService.isDefaultNetworkActive();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002774 } catch (RemoteException e) {
2775 throw e.rethrowFromSystemServer();
2776 }
2777 }
2778
2779 /**
2780 * {@hide}
2781 */
2782 public ConnectivityManager(Context context, IConnectivityManager service) {
markchiend2015662022-04-26 18:08:03 +08002783 this(context, service, true /* newStatic */);
2784 }
2785
2786 private ConnectivityManager(Context context, IConnectivityManager service, boolean newStatic) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00002787 mContext = Objects.requireNonNull(context, "missing context");
2788 mService = Objects.requireNonNull(service, "missing IConnectivityManager");
markchiend2015662022-04-26 18:08:03 +08002789 // sInstance is accessed without a lock, so it may actually be reassigned several times with
2790 // different ConnectivityManager, but that's still OK considering its usage.
2791 if (sInstance == null && newStatic) {
2792 final Context appContext = mContext.getApplicationContext();
2793 // Don't create static ConnectivityManager instance again to prevent infinite loop.
2794 // If the application context is null, we're either in the system process or
2795 // it's the application context very early in app initialization. In both these
2796 // cases, the passed-in Context will not be freed, so it's safe to pass it to the
2797 // service. http://b/27532714 .
2798 sInstance = new ConnectivityManager(appContext != null ? appContext : context, service,
2799 false /* newStatic */);
2800 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002801 }
2802
2803 /** {@hide} */
2804 @UnsupportedAppUsage
2805 public static ConnectivityManager from(Context context) {
2806 return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2807 }
2808
2809 /** @hide */
2810 public NetworkRequest getDefaultRequest() {
2811 try {
2812 // This is not racy as the default request is final in ConnectivityService.
2813 return mService.getDefaultRequest();
2814 } catch (RemoteException e) {
2815 throw e.rethrowFromSystemServer();
2816 }
2817 }
2818
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002819 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09002820 * Check if the package is allowed to write settings. This also records that such an access
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002821 * happened.
2822 *
2823 * @return {@code true} iff the package is allowed to write settings.
2824 */
2825 // TODO: Remove method and replace with direct call once R code is pushed to AOSP
2826 private static boolean checkAndNoteWriteSettingsOperation(@NonNull Context context, int uid,
2827 @NonNull String callingPackage, @Nullable String callingAttributionTag,
2828 boolean throwException) {
2829 return Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPackage,
Remi NGUYEN VANa522fc22021-02-01 10:25:24 +00002830 callingAttributionTag, throwException);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002831 }
2832
2833 /**
2834 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2835 * situations where a Context pointer is unavailable.
2836 * @hide
2837 */
2838 @Deprecated
2839 static ConnectivityManager getInstanceOrNull() {
2840 return sInstance;
2841 }
2842
2843 /**
2844 * @deprecated - use getSystemService. This is a kludge to support static access in certain
2845 * situations where a Context pointer is unavailable.
2846 * @hide
2847 */
2848 @Deprecated
2849 @UnsupportedAppUsage
2850 private static ConnectivityManager getInstance() {
2851 if (getInstanceOrNull() == null) {
2852 throw new IllegalStateException("No ConnectivityManager yet constructed");
2853 }
2854 return getInstanceOrNull();
2855 }
2856
2857 /**
2858 * Get the set of tetherable, available interfaces. This list is limited by
2859 * device configuration and current interface existence.
2860 *
2861 * @return an array of 0 or more Strings of tetherable interface names.
2862 *
2863 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2864 * {@hide}
2865 */
2866 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2867 @UnsupportedAppUsage
2868 @Deprecated
2869 public String[] getTetherableIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002870 return getTetheringManager().getTetherableIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002871 }
2872
2873 /**
2874 * Get the set of tethered interfaces.
2875 *
2876 * @return an array of 0 or more String of currently tethered interface names.
2877 *
2878 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfacesChanged(List)} instead.
2879 * {@hide}
2880 */
2881 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2882 @UnsupportedAppUsage
2883 @Deprecated
2884 public String[] getTetheredIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002885 return getTetheringManager().getTetheredIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002886 }
2887
2888 /**
2889 * Get the set of interface names which attempted to tether but
2890 * failed. Re-attempting to tether may cause them to reset to the Tethered
2891 * state. Alternatively, causing the interface to be destroyed and recreated
2892 * may cause them to reset to the available state.
2893 * {@link ConnectivityManager#getLastTetherError} can be used to get more
2894 * information on the cause of the errors.
2895 *
2896 * @return an array of 0 or more String indicating the interface names
2897 * which failed to tether.
2898 *
2899 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
2900 * {@hide}
2901 */
2902 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
2903 @UnsupportedAppUsage
2904 @Deprecated
2905 public String[] getTetheringErroredIfaces() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002906 return getTetheringManager().getTetheringErroredIfaces();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002907 }
2908
2909 /**
2910 * Get the set of tethered dhcp ranges.
2911 *
2912 * @deprecated This method is not supported.
2913 * TODO: remove this function when all of clients are removed.
2914 * {@hide}
2915 */
2916 @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
2917 @Deprecated
2918 public String[] getTetheredDhcpRanges() {
2919 throw new UnsupportedOperationException("getTetheredDhcpRanges is not supported");
2920 }
2921
2922 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09002923 * Attempt to tether the named interface. This will set up a dhcp server
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002924 * on the interface, forward and NAT IP packets and forward DNS requests
2925 * to the best active upstream network interface. Note that if no upstream
2926 * IP network interface is available, dhcp will still run and traffic will be
2927 * allowed between the tethered devices and this device, though upstream net
2928 * access will of course fail until an upstream network interface becomes
2929 * active.
2930 *
2931 * <p>This method requires the caller to hold either the
2932 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2933 * or the ability to modify system settings as determined by
2934 * {@link android.provider.Settings.System#canWrite}.</p>
2935 *
2936 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2937 * and WifiStateMachine which need direct access. All other clients should use
2938 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2939 * logic.</p>
2940 *
2941 * @param iface the interface name to tether.
2942 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2943 * @deprecated Use {@link TetheringManager#startTethering} instead
2944 *
2945 * {@hide}
2946 */
2947 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2948 @Deprecated
2949 public int tether(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002950 return getTetheringManager().tether(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002951 }
2952
2953 /**
2954 * Stop tethering the named interface.
2955 *
2956 * <p>This method requires the caller to hold either the
2957 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
2958 * or the ability to modify system settings as determined by
2959 * {@link android.provider.Settings.System#canWrite}.</p>
2960 *
2961 * <p>WARNING: New clients should not use this function. The only usages should be in PanService
2962 * and WifiStateMachine which need direct access. All other clients should use
2963 * {@link #startTethering} and {@link #stopTethering} which encapsulate proper provisioning
2964 * logic.</p>
2965 *
2966 * @param iface the interface name to untether.
2967 * @return error a {@code TETHER_ERROR} value indicating success or failure type
2968 *
2969 * {@hide}
2970 */
2971 @UnsupportedAppUsage
2972 @Deprecated
2973 public int untether(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09002974 return getTetheringManager().untether(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09002975 }
2976
2977 /**
2978 * Check if the device allows for tethering. It may be disabled via
2979 * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or
2980 * due to device configuration.
2981 *
2982 * <p>If this app does not have permission to use this API, it will always
2983 * return false rather than throw an exception.</p>
2984 *
2985 * <p>If the device has a hotspot provisioning app, the caller is required to hold the
2986 * {@link android.Manifest.permission.TETHER_PRIVILEGED} permission.</p>
2987 *
2988 * <p>Otherwise, this method requires the caller to hold the ability to modify system
2989 * settings as determined by {@link android.provider.Settings.System#canWrite}.</p>
2990 *
2991 * @return a boolean - {@code true} indicating Tethering is supported.
2992 *
2993 * @deprecated Use {@link TetheringEventCallback#onTetheringSupported(boolean)} instead.
2994 * {@hide}
2995 */
2996 @SystemApi
2997 @RequiresPermission(anyOf = {android.Manifest.permission.TETHER_PRIVILEGED,
2998 android.Manifest.permission.WRITE_SETTINGS})
2999 public boolean isTetheringSupported() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003000 return getTetheringManager().isTetheringSupported();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003001 }
3002
3003 /**
3004 * Callback for use with {@link #startTethering} to find out whether tethering succeeded.
3005 *
3006 * @deprecated Use {@link TetheringManager.StartTetheringCallback} instead.
3007 * @hide
3008 */
3009 @SystemApi
3010 @Deprecated
3011 public static abstract class OnStartTetheringCallback {
3012 /**
3013 * Called when tethering has been successfully started.
3014 */
3015 public void onTetheringStarted() {}
3016
3017 /**
3018 * Called when starting tethering failed.
3019 */
3020 public void onTetheringFailed() {}
3021 }
3022
3023 /**
3024 * Convenient overload for
3025 * {@link #startTethering(int, boolean, OnStartTetheringCallback, Handler)} which passes a null
3026 * handler to run on the current thread's {@link Looper}.
3027 *
3028 * @deprecated Use {@link TetheringManager#startTethering} instead.
3029 * @hide
3030 */
3031 @SystemApi
3032 @Deprecated
3033 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3034 public void startTethering(int type, boolean showProvisioningUi,
3035 final OnStartTetheringCallback callback) {
3036 startTethering(type, showProvisioningUi, callback, null);
3037 }
3038
3039 /**
3040 * Runs tether provisioning for the given type if needed and then starts tethering if
3041 * the check succeeds. If no carrier provisioning is required for tethering, tethering is
3042 * enabled immediately. If provisioning fails, tethering will not be enabled. It also
3043 * schedules tether provisioning re-checks if appropriate.
3044 *
3045 * @param type The type of tethering to start. Must be one of
3046 * {@link ConnectivityManager.TETHERING_WIFI},
3047 * {@link ConnectivityManager.TETHERING_USB}, or
3048 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
3049 * @param showProvisioningUi a boolean indicating to show the provisioning app UI if there
3050 * is one. This should be true the first time this function is called and also any time
3051 * the user can see this UI. It gives users information from their carrier about the
3052 * check failing and how they can sign up for tethering if possible.
3053 * @param callback an {@link OnStartTetheringCallback} which will be called to notify the caller
3054 * of the result of trying to tether.
3055 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
3056 *
3057 * @deprecated Use {@link TetheringManager#startTethering} instead.
3058 * @hide
3059 */
3060 @SystemApi
3061 @Deprecated
3062 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3063 public void startTethering(int type, boolean showProvisioningUi,
3064 final OnStartTetheringCallback callback, Handler handler) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003065 Objects.requireNonNull(callback, "OnStartTetheringCallback cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003066
3067 final Executor executor = new Executor() {
3068 @Override
3069 public void execute(Runnable command) {
3070 if (handler == null) {
3071 command.run();
3072 } else {
3073 handler.post(command);
3074 }
3075 }
3076 };
3077
3078 final StartTetheringCallback tetheringCallback = new StartTetheringCallback() {
3079 @Override
3080 public void onTetheringStarted() {
3081 callback.onTetheringStarted();
3082 }
3083
3084 @Override
3085 public void onTetheringFailed(final int error) {
3086 callback.onTetheringFailed();
3087 }
3088 };
3089
3090 final TetheringRequest request = new TetheringRequest.Builder(type)
3091 .setShouldShowEntitlementUi(showProvisioningUi).build();
3092
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003093 getTetheringManager().startTethering(request, executor, tetheringCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003094 }
3095
3096 /**
3097 * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if
3098 * applicable.
3099 *
3100 * @param type The type of tethering to stop. Must be one of
3101 * {@link ConnectivityManager.TETHERING_WIFI},
3102 * {@link ConnectivityManager.TETHERING_USB}, or
3103 * {@link ConnectivityManager.TETHERING_BLUETOOTH}.
3104 *
3105 * @deprecated Use {@link TetheringManager#stopTethering} instead.
3106 * @hide
3107 */
3108 @SystemApi
3109 @Deprecated
3110 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3111 public void stopTethering(int type) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003112 getTetheringManager().stopTethering(type);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003113 }
3114
3115 /**
3116 * Callback for use with {@link registerTetheringEventCallback} to find out tethering
3117 * upstream status.
3118 *
3119 * @deprecated Use {@link TetheringManager#OnTetheringEventCallback} instead.
3120 * @hide
3121 */
3122 @SystemApi
3123 @Deprecated
3124 public abstract static class OnTetheringEventCallback {
3125
3126 /**
3127 * Called when tethering upstream changed. This can be called multiple times and can be
3128 * called any time.
3129 *
3130 * @param network the {@link Network} of tethering upstream. Null means tethering doesn't
3131 * have any upstream.
3132 */
3133 public void onUpstreamChanged(@Nullable Network network) {}
3134 }
3135
3136 @GuardedBy("mTetheringEventCallbacks")
3137 private final ArrayMap<OnTetheringEventCallback, TetheringEventCallback>
3138 mTetheringEventCallbacks = new ArrayMap<>();
3139
3140 /**
3141 * Start listening to tethering change events. Any new added callback will receive the last
3142 * tethering status right away. If callback is registered when tethering has no upstream or
3143 * disabled, {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called
3144 * with a null argument. The same callback object cannot be registered twice.
3145 *
3146 * @param executor the executor on which callback will be invoked.
3147 * @param callback the callback to be called when tethering has change events.
3148 *
3149 * @deprecated Use {@link TetheringManager#registerTetheringEventCallback} instead.
3150 * @hide
3151 */
3152 @SystemApi
3153 @Deprecated
3154 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3155 public void registerTetheringEventCallback(
3156 @NonNull @CallbackExecutor Executor executor,
3157 @NonNull final OnTetheringEventCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003158 Objects.requireNonNull(callback, "OnTetheringEventCallback cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003159
3160 final TetheringEventCallback tetherCallback =
3161 new TetheringEventCallback() {
3162 @Override
3163 public void onUpstreamChanged(@Nullable Network network) {
3164 callback.onUpstreamChanged(network);
3165 }
3166 };
3167
3168 synchronized (mTetheringEventCallbacks) {
3169 mTetheringEventCallbacks.put(callback, tetherCallback);
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003170 getTetheringManager().registerTetheringEventCallback(executor, tetherCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003171 }
3172 }
3173
3174 /**
3175 * Remove tethering event callback previously registered with
3176 * {@link #registerTetheringEventCallback}.
3177 *
3178 * @param callback previously registered callback.
3179 *
3180 * @deprecated Use {@link TetheringManager#unregisterTetheringEventCallback} instead.
3181 * @hide
3182 */
3183 @SystemApi
3184 @Deprecated
3185 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3186 public void unregisterTetheringEventCallback(
3187 @NonNull final OnTetheringEventCallback callback) {
3188 Objects.requireNonNull(callback, "The callback must be non-null");
3189 synchronized (mTetheringEventCallbacks) {
3190 final TetheringEventCallback tetherCallback =
3191 mTetheringEventCallbacks.remove(callback);
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003192 getTetheringManager().unregisterTetheringEventCallback(tetherCallback);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003193 }
3194 }
3195
3196
3197 /**
3198 * Get the list of regular expressions that define any tetherable
3199 * USB network interfaces. If USB tethering is not supported by the
3200 * device, this list should be empty.
3201 *
3202 * @return an array of 0 or more regular expression Strings defining
3203 * what interfaces are considered tetherable usb interfaces.
3204 *
3205 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
3206 * {@hide}
3207 */
3208 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3209 @UnsupportedAppUsage
3210 @Deprecated
3211 public String[] getTetherableUsbRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003212 return getTetheringManager().getTetherableUsbRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003213 }
3214
3215 /**
3216 * Get the list of regular expressions that define any tetherable
3217 * Wifi network interfaces. If Wifi tethering is not supported by the
3218 * device, this list should be empty.
3219 *
3220 * @return an array of 0 or more regular expression Strings defining
3221 * what interfaces are considered tetherable wifi interfaces.
3222 *
3223 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged} instead.
3224 * {@hide}
3225 */
3226 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3227 @UnsupportedAppUsage
3228 @Deprecated
3229 public String[] getTetherableWifiRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003230 return getTetheringManager().getTetherableWifiRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003231 }
3232
3233 /**
3234 * Get the list of regular expressions that define any tetherable
3235 * Bluetooth network interfaces. If Bluetooth tethering is not supported by the
3236 * device, this list should be empty.
3237 *
3238 * @return an array of 0 or more regular expression Strings defining
3239 * what interfaces are considered tetherable bluetooth interfaces.
3240 *
3241 * @deprecated Use {@link TetheringEventCallback#onTetherableInterfaceRegexpsChanged(
3242 *TetheringManager.TetheringInterfaceRegexps)} instead.
3243 * {@hide}
3244 */
3245 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3246 @UnsupportedAppUsage
3247 @Deprecated
3248 public String[] getTetherableBluetoothRegexs() {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003249 return getTetheringManager().getTetherableBluetoothRegexs();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003250 }
3251
3252 /**
3253 * Attempt to both alter the mode of USB and Tethering of USB. A
3254 * utility method to deal with some of the complexity of USB - will
3255 * attempt to switch to Rndis and subsequently tether the resulting
3256 * interface on {@code true} or turn off tethering and switch off
3257 * Rndis on {@code false}.
3258 *
3259 * <p>This method requires the caller to hold either the
3260 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
3261 * or the ability to modify system settings as determined by
3262 * {@link android.provider.Settings.System#canWrite}.</p>
3263 *
3264 * @param enable a boolean - {@code true} to enable tethering
3265 * @return error a {@code TETHER_ERROR} value indicating success or failure type
3266 * @deprecated Use {@link TetheringManager#startTethering} instead
3267 *
3268 * {@hide}
3269 */
3270 @UnsupportedAppUsage
3271 @Deprecated
3272 public int setUsbTethering(boolean enable) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003273 return getTetheringManager().setUsbTethering(enable);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003274 }
3275
3276 /**
3277 * @deprecated Use {@link TetheringManager#TETHER_ERROR_NO_ERROR}.
3278 * {@hide}
3279 */
3280 @SystemApi
3281 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003282 public static final int TETHER_ERROR_NO_ERROR = 0;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003283 /**
3284 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
3285 * {@hide}
3286 */
3287 @Deprecated
3288 public static final int TETHER_ERROR_UNKNOWN_IFACE =
3289 TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
3290 /**
3291 * @deprecated Use {@link TetheringManager#TETHER_ERROR_SERVICE_UNAVAIL}.
3292 * {@hide}
3293 */
3294 @Deprecated
3295 public static final int TETHER_ERROR_SERVICE_UNAVAIL =
3296 TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
3297 /**
3298 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNSUPPORTED}.
3299 * {@hide}
3300 */
3301 @Deprecated
3302 public static final int TETHER_ERROR_UNSUPPORTED = TetheringManager.TETHER_ERROR_UNSUPPORTED;
3303 /**
3304 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNAVAIL_IFACE}.
3305 * {@hide}
3306 */
3307 @Deprecated
3308 public static final int TETHER_ERROR_UNAVAIL_IFACE =
3309 TetheringManager.TETHER_ERROR_UNAVAIL_IFACE;
3310 /**
3311 * @deprecated Use {@link TetheringManager#TETHER_ERROR_INTERNAL_ERROR}.
3312 * {@hide}
3313 */
3314 @Deprecated
3315 public static final int TETHER_ERROR_MASTER_ERROR =
3316 TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
3317 /**
3318 * @deprecated Use {@link TetheringManager#TETHER_ERROR_TETHER_IFACE_ERROR}.
3319 * {@hide}
3320 */
3321 @Deprecated
3322 public static final int TETHER_ERROR_TETHER_IFACE_ERROR =
3323 TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
3324 /**
3325 * @deprecated Use {@link TetheringManager#TETHER_ERROR_UNTETHER_IFACE_ERROR}.
3326 * {@hide}
3327 */
3328 @Deprecated
3329 public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR =
3330 TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
3331 /**
3332 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENABLE_FORWARDING_ERROR}.
3333 * {@hide}
3334 */
3335 @Deprecated
3336 public static final int TETHER_ERROR_ENABLE_NAT_ERROR =
3337 TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
3338 /**
3339 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DISABLE_FORWARDING_ERROR}.
3340 * {@hide}
3341 */
3342 @Deprecated
3343 public static final int TETHER_ERROR_DISABLE_NAT_ERROR =
3344 TetheringManager.TETHER_ERROR_DISABLE_FORWARDING_ERROR;
3345 /**
3346 * @deprecated Use {@link TetheringManager#TETHER_ERROR_IFACE_CFG_ERROR}.
3347 * {@hide}
3348 */
3349 @Deprecated
3350 public static final int TETHER_ERROR_IFACE_CFG_ERROR =
3351 TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
3352 /**
3353 * @deprecated Use {@link TetheringManager#TETHER_ERROR_PROVISIONING_FAILED}.
3354 * {@hide}
3355 */
3356 @SystemApi
3357 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003358 public static final int TETHER_ERROR_PROVISION_FAILED = 11;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003359 /**
3360 * @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
3361 * {@hide}
3362 */
3363 @Deprecated
3364 public static final int TETHER_ERROR_DHCPSERVER_ERROR =
3365 TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
3366 /**
3367 * @deprecated Use {@link TetheringManager#TETHER_ERROR_ENTITLEMENT_UNKNOWN}.
3368 * {@hide}
3369 */
3370 @SystemApi
3371 @Deprecated
Remi NGUYEN VAN71ced8e2021-02-15 18:52:06 +09003372 public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003373
3374 /**
3375 * Get a more detailed error code after a Tethering or Untethering
3376 * request asynchronously failed.
3377 *
3378 * @param iface The name of the interface of interest
3379 * @return error The error code of the last error tethering or untethering the named
3380 * interface
3381 *
3382 * @deprecated Use {@link TetheringEventCallback#onError(String, int)} instead.
3383 * {@hide}
3384 */
3385 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3386 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
3387 @Deprecated
3388 public int getLastTetherError(String iface) {
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003389 int error = getTetheringManager().getLastTetherError(iface);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003390 if (error == TetheringManager.TETHER_ERROR_UNKNOWN_TYPE) {
3391 // TETHER_ERROR_UNKNOWN_TYPE was introduced with TetheringManager and has never been
3392 // returned by ConnectivityManager. Convert it to the legacy TETHER_ERROR_UNKNOWN_IFACE
3393 // instead.
3394 error = TetheringManager.TETHER_ERROR_UNKNOWN_IFACE;
3395 }
3396 return error;
3397 }
3398
3399 /** @hide */
3400 @Retention(RetentionPolicy.SOURCE)
3401 @IntDef(value = {
3402 TETHER_ERROR_NO_ERROR,
3403 TETHER_ERROR_PROVISION_FAILED,
3404 TETHER_ERROR_ENTITLEMENT_UNKONWN,
3405 })
3406 public @interface EntitlementResultCode {
3407 }
3408
3409 /**
3410 * Callback for use with {@link #getLatestTetheringEntitlementResult} to find out whether
3411 * entitlement succeeded.
3412 *
3413 * @deprecated Use {@link TetheringManager#OnTetheringEntitlementResultListener} instead.
3414 * @hide
3415 */
3416 @SystemApi
3417 @Deprecated
3418 public interface OnTetheringEntitlementResultListener {
3419 /**
3420 * Called to notify entitlement result.
3421 *
3422 * @param resultCode an int value of entitlement result. It may be one of
3423 * {@link #TETHER_ERROR_NO_ERROR},
3424 * {@link #TETHER_ERROR_PROVISION_FAILED}, or
3425 * {@link #TETHER_ERROR_ENTITLEMENT_UNKONWN}.
3426 */
3427 void onTetheringEntitlementResult(@EntitlementResultCode int resultCode);
3428 }
3429
3430 /**
3431 * Get the last value of the entitlement check on this downstream. If the cached value is
Chalard Jean0c7ebe92022-08-03 14:45:47 +09003432 * {@link #TETHER_ERROR_NO_ERROR} or showEntitlementUi argument is false, this just returns the
3433 * cached value. Otherwise, a UI-based entitlement check will be performed. It is not
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003434 * guaranteed that the UI-based entitlement check will complete in any specific time period
Chalard Jean0c7ebe92022-08-03 14:45:47 +09003435 * and it may in fact never complete. Any successful entitlement check the platform performs for
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003436 * any reason will update the cached value.
3437 *
3438 * @param type the downstream type of tethering. Must be one of
3439 * {@link #TETHERING_WIFI},
3440 * {@link #TETHERING_USB}, or
3441 * {@link #TETHERING_BLUETOOTH}.
3442 * @param showEntitlementUi a boolean indicating whether to run UI-based entitlement check.
3443 * @param executor the executor on which callback will be invoked.
3444 * @param listener an {@link OnTetheringEntitlementResultListener} which will be called to
3445 * notify the caller of the result of entitlement check. The listener may be called zero
3446 * or one time.
3447 * @deprecated Use {@link TetheringManager#requestLatestTetheringEntitlementResult} instead.
3448 * {@hide}
3449 */
3450 @SystemApi
3451 @Deprecated
3452 @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
3453 public void getLatestTetheringEntitlementResult(int type, boolean showEntitlementUi,
3454 @NonNull @CallbackExecutor Executor executor,
3455 @NonNull final OnTetheringEntitlementResultListener listener) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003456 Objects.requireNonNull(listener, "TetheringEntitlementResultListener cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003457 ResultReceiver wrappedListener = new ResultReceiver(null) {
3458 @Override
3459 protected void onReceiveResult(int resultCode, Bundle resultData) {
lucaslineaff72d2021-03-04 09:38:21 +08003460 final long token = Binder.clearCallingIdentity();
3461 try {
3462 executor.execute(() -> {
3463 listener.onTetheringEntitlementResult(resultCode);
3464 });
3465 } finally {
3466 Binder.restoreCallingIdentity(token);
3467 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003468 }
3469 };
3470
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09003471 getTetheringManager().requestLatestTetheringEntitlementResult(type, wrappedListener,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003472 showEntitlementUi);
3473 }
3474
3475 /**
3476 * Report network connectivity status. This is currently used only
3477 * to alter status bar UI.
3478 * <p>This method requires the caller to hold the permission
3479 * {@link android.Manifest.permission#STATUS_BAR}.
3480 *
3481 * @param networkType The type of network you want to report on
3482 * @param percentage The quality of the connection 0 is bad, 100 is good
3483 * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
3484 * {@hide}
3485 */
3486 public void reportInetCondition(int networkType, int percentage) {
3487 printStackTrace();
3488 try {
3489 mService.reportInetCondition(networkType, percentage);
3490 } catch (RemoteException e) {
3491 throw e.rethrowFromSystemServer();
3492 }
3493 }
3494
3495 /**
3496 * Report a problem network to the framework. This provides a hint to the system
3497 * that there might be connectivity problems on this network and may cause
3498 * the framework to re-evaluate network connectivity and/or switch to another
3499 * network.
3500 *
3501 * @param network The {@link Network} the application was attempting to use
3502 * or {@code null} to indicate the current default network.
3503 * @deprecated Use {@link #reportNetworkConnectivity} which allows reporting both
3504 * working and non-working connectivity.
3505 */
3506 @Deprecated
3507 public void reportBadNetwork(@Nullable Network network) {
3508 printStackTrace();
3509 try {
3510 // One of these will be ignored because it matches system's current state.
3511 // The other will trigger the necessary reevaluation.
3512 mService.reportNetworkConnectivity(network, true);
3513 mService.reportNetworkConnectivity(network, false);
3514 } catch (RemoteException e) {
3515 throw e.rethrowFromSystemServer();
3516 }
3517 }
3518
3519 /**
3520 * Report to the framework whether a network has working connectivity.
3521 * This provides a hint to the system that a particular network is providing
3522 * working connectivity or not. In response the framework may re-evaluate
3523 * the network's connectivity and might take further action thereafter.
3524 *
3525 * @param network The {@link Network} the application was attempting to use
3526 * or {@code null} to indicate the current default network.
3527 * @param hasConnectivity {@code true} if the application was able to successfully access the
3528 * Internet using {@code network} or {@code false} if not.
3529 */
3530 public void reportNetworkConnectivity(@Nullable Network network, boolean hasConnectivity) {
3531 printStackTrace();
3532 try {
3533 mService.reportNetworkConnectivity(network, hasConnectivity);
3534 } catch (RemoteException e) {
3535 throw e.rethrowFromSystemServer();
3536 }
3537 }
3538
3539 /**
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003540 * Set a network-independent global HTTP proxy.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003541 *
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003542 * This sets an HTTP proxy that applies to all networks and overrides any network-specific
3543 * proxy. If set, HTTP libraries that are proxy-aware will use this global proxy when
3544 * accessing any network, regardless of what the settings for that network are.
3545 *
3546 * Note that HTTP proxies are by nature typically network-dependent, and setting a global
3547 * proxy is likely to break networking on multiple networks. This method is only meant
3548 * for device policy clients looking to do general internal filtering or similar use cases.
3549 *
chiachangwang9473c592022-07-15 02:25:52 +00003550 * @see #getGlobalProxy
3551 * @see LinkProperties#getHttpProxy
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003552 *
3553 * @param p A {@link ProxyInfo} object defining the new global HTTP proxy. Calling this
3554 * method with a {@code null} value will clear the global HTTP proxy.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003555 * @hide
3556 */
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003557 // Used by Device Policy Manager to set the global proxy.
Chiachang Wangf9294e72021-03-18 09:44:34 +08003558 @SystemApi(client = MODULE_LIBRARIES)
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003559 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Chalard Jeane1ce6ae2021-03-17 17:03:34 +09003560 public void setGlobalProxy(@Nullable final ProxyInfo p) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003561 try {
3562 mService.setGlobalProxy(p);
3563 } catch (RemoteException e) {
3564 throw e.rethrowFromSystemServer();
3565 }
3566 }
3567
3568 /**
3569 * Retrieve any network-independent global HTTP proxy.
3570 *
3571 * @return {@link ProxyInfo} for the current global HTTP proxy or {@code null}
3572 * if no global HTTP proxy is set.
3573 * @hide
3574 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08003575 @SystemApi(client = MODULE_LIBRARIES)
3576 @Nullable
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003577 public ProxyInfo getGlobalProxy() {
3578 try {
3579 return mService.getGlobalProxy();
3580 } catch (RemoteException e) {
3581 throw e.rethrowFromSystemServer();
3582 }
3583 }
3584
3585 /**
3586 * Retrieve the global HTTP proxy, or if no global HTTP proxy is set, a
3587 * network-specific HTTP proxy. If {@code network} is null, the
3588 * network-specific proxy returned is the proxy of the default active
3589 * network.
3590 *
3591 * @return {@link ProxyInfo} for the current global HTTP proxy, or if no
3592 * global HTTP proxy is set, {@code ProxyInfo} for {@code network},
3593 * or when {@code network} is {@code null},
3594 * the {@code ProxyInfo} for the default active network. Returns
3595 * {@code null} when no proxy applies or the caller doesn't have
3596 * permission to use {@code network}.
3597 * @hide
3598 */
3599 public ProxyInfo getProxyForNetwork(Network network) {
3600 try {
3601 return mService.getProxyForNetwork(network);
3602 } catch (RemoteException e) {
3603 throw e.rethrowFromSystemServer();
3604 }
3605 }
3606
3607 /**
3608 * Get the current default HTTP proxy settings. If a global proxy is set it will be returned,
3609 * otherwise if this process is bound to a {@link Network} using
3610 * {@link #bindProcessToNetwork} then that {@code Network}'s proxy is returned, otherwise
3611 * the default network's proxy is returned.
3612 *
3613 * @return the {@link ProxyInfo} for the current HTTP proxy, or {@code null} if no
3614 * HTTP proxy is active.
3615 */
3616 @Nullable
3617 public ProxyInfo getDefaultProxy() {
3618 return getProxyForNetwork(getBoundNetworkForProcess());
3619 }
3620
3621 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09003622 * Returns whether the hardware supports the given network type.
3623 *
3624 * This doesn't indicate there is coverage or such a network is available, just whether the
3625 * hardware supports it. For example a GSM phone without a SIM card will return {@code true}
3626 * for mobile data, but a WiFi only tablet would return {@code false}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003627 *
3628 * @param networkType The network type we'd like to check
3629 * @return {@code true} if supported, else {@code false}
3630 * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
3631 * @hide
3632 */
3633 @Deprecated
3634 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3635 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
3636 public boolean isNetworkSupported(int networkType) {
3637 try {
3638 return mService.isNetworkSupported(networkType);
3639 } catch (RemoteException e) {
3640 throw e.rethrowFromSystemServer();
3641 }
3642 }
3643
3644 /**
3645 * Returns if the currently active data network is metered. A network is
3646 * classified as metered when the user is sensitive to heavy data usage on
3647 * that connection due to monetary costs, data limitations or
3648 * battery/performance issues. You should check this before doing large
3649 * data transfers, and warn the user or delay the operation until another
3650 * network is available.
3651 *
3652 * @return {@code true} if large transfers should be avoided, otherwise
3653 * {@code false}.
3654 */
3655 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
3656 public boolean isActiveNetworkMetered() {
3657 try {
3658 return mService.isActiveNetworkMetered();
3659 } catch (RemoteException e) {
3660 throw e.rethrowFromSystemServer();
3661 }
3662 }
3663
3664 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003665 * Set sign in error notification to visible or invisible
3666 *
3667 * @hide
3668 * @deprecated Doesn't properly deal with multiple connected networks of the same type.
3669 */
3670 @Deprecated
3671 public void setProvisioningNotificationVisible(boolean visible, int networkType,
3672 String action) {
3673 try {
3674 mService.setProvisioningNotificationVisible(visible, networkType, action);
3675 } catch (RemoteException e) {
3676 throw e.rethrowFromSystemServer();
3677 }
3678 }
3679
3680 /**
3681 * Set the value for enabling/disabling airplane mode
3682 *
3683 * @param enable whether to enable airplane mode or not
3684 *
3685 * @hide
3686 */
3687 @RequiresPermission(anyOf = {
3688 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3689 android.Manifest.permission.NETWORK_SETTINGS,
3690 android.Manifest.permission.NETWORK_SETUP_WIZARD,
3691 android.Manifest.permission.NETWORK_STACK})
3692 @SystemApi
3693 public void setAirplaneMode(boolean enable) {
3694 try {
3695 mService.setAirplaneMode(enable);
3696 } catch (RemoteException e) {
3697 throw e.rethrowFromSystemServer();
3698 }
3699 }
3700
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003701 /**
3702 * Registers the specified {@link NetworkProvider}.
3703 * Each listener must only be registered once. The listener can be unregistered with
3704 * {@link #unregisterNetworkProvider}.
3705 *
3706 * @param provider the provider to register
3707 * @return the ID of the provider. This ID must be used by the provider when registering
3708 * {@link android.net.NetworkAgent}s.
3709 * @hide
3710 */
3711 @SystemApi
3712 @RequiresPermission(anyOf = {
3713 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3714 android.Manifest.permission.NETWORK_FACTORY})
3715 public int registerNetworkProvider(@NonNull NetworkProvider provider) {
3716 if (provider.getProviderId() != NetworkProvider.ID_NONE) {
3717 throw new IllegalStateException("NetworkProviders can only be registered once");
3718 }
3719
3720 try {
3721 int providerId = mService.registerNetworkProvider(provider.getMessenger(),
3722 provider.getName());
3723 provider.setProviderId(providerId);
3724 } catch (RemoteException e) {
3725 throw e.rethrowFromSystemServer();
3726 }
3727 return provider.getProviderId();
3728 }
3729
3730 /**
3731 * Unregisters the specified NetworkProvider.
3732 *
3733 * @param provider the provider to unregister
3734 * @hide
3735 */
3736 @SystemApi
3737 @RequiresPermission(anyOf = {
3738 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3739 android.Manifest.permission.NETWORK_FACTORY})
3740 public void unregisterNetworkProvider(@NonNull NetworkProvider provider) {
3741 try {
3742 mService.unregisterNetworkProvider(provider.getMessenger());
3743 } catch (RemoteException e) {
3744 throw e.rethrowFromSystemServer();
3745 }
3746 provider.setProviderId(NetworkProvider.ID_NONE);
3747 }
3748
Chalard Jeand1b498b2021-01-05 08:40:09 +09003749 /**
3750 * Register or update a network offer with ConnectivityService.
3751 *
3752 * ConnectivityService keeps track of offers made by the various providers and matches
Chalard Jean61e231f2021-03-24 17:43:10 +09003753 * them to networking requests made by apps or the system. A callback identifies an offer
3754 * uniquely, and later calls with the same callback update the offer. The provider supplies a
3755 * score and the capabilities of the network it might be able to bring up ; these act as
3756 * filters used by ConnectivityService to only send those requests that can be fulfilled by the
Chalard Jeand1b498b2021-01-05 08:40:09 +09003757 * provider.
3758 *
3759 * The provider is under no obligation to be able to bring up the network it offers at any
3760 * given time. Instead, this mechanism is meant to limit requests received by providers
3761 * to those they actually have a chance to fulfill, as providers don't have a way to compare
3762 * the quality of the network satisfying a given request to their own offer.
3763 *
3764 * An offer can be updated by calling this again with the same callback object. This is
3765 * similar to calling unofferNetwork and offerNetwork again, but will only update the
3766 * provider with the changes caused by the changes in the offer.
3767 *
3768 * @param provider The provider making this offer.
3769 * @param score The prospective score of the network.
3770 * @param caps The prospective capabilities of the network.
3771 * @param callback The callback to call when this offer is needed or unneeded.
Chalard Jean428b9132021-01-12 10:58:56 +09003772 * @hide exposed via the NetworkProvider class.
Chalard Jeand1b498b2021-01-05 08:40:09 +09003773 */
3774 @RequiresPermission(anyOf = {
3775 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3776 android.Manifest.permission.NETWORK_FACTORY})
Chalard Jean148dcce2021-03-22 22:44:02 +09003777 public void offerNetwork(@NonNull final int providerId,
Chalard Jeand1b498b2021-01-05 08:40:09 +09003778 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
3779 @NonNull final INetworkOfferCallback callback) {
3780 try {
Chalard Jean148dcce2021-03-22 22:44:02 +09003781 mService.offerNetwork(providerId,
Chalard Jeand1b498b2021-01-05 08:40:09 +09003782 Objects.requireNonNull(score, "null score"),
3783 Objects.requireNonNull(caps, "null caps"),
3784 Objects.requireNonNull(callback, "null callback"));
3785 } catch (RemoteException e) {
3786 throw e.rethrowFromSystemServer();
3787 }
3788 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003789
Chalard Jeand1b498b2021-01-05 08:40:09 +09003790 /**
3791 * Withdraw a network offer made with {@link #offerNetwork}.
3792 *
3793 * @param callback The callback passed at registration time. This must be the same object
3794 * that was passed to {@link #offerNetwork}
Chalard Jean428b9132021-01-12 10:58:56 +09003795 * @hide exposed via the NetworkProvider class.
Chalard Jeand1b498b2021-01-05 08:40:09 +09003796 */
3797 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
3798 try {
3799 mService.unofferNetwork(Objects.requireNonNull(callback));
3800 } catch (RemoteException e) {
3801 throw e.rethrowFromSystemServer();
3802 }
3803 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003804 /** @hide exposed via the NetworkProvider class. */
3805 @RequiresPermission(anyOf = {
3806 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3807 android.Manifest.permission.NETWORK_FACTORY})
3808 public void declareNetworkRequestUnfulfillable(@NonNull NetworkRequest request) {
3809 try {
3810 mService.declareNetworkRequestUnfulfillable(request);
3811 } catch (RemoteException e) {
3812 throw e.rethrowFromSystemServer();
3813 }
3814 }
3815
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003816 /**
3817 * @hide
3818 * Register a NetworkAgent with ConnectivityService.
3819 * @return Network corresponding to NetworkAgent.
3820 */
3821 @RequiresPermission(anyOf = {
3822 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3823 android.Manifest.permission.NETWORK_FACTORY})
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09003824 public Network registerNetworkAgent(@NonNull INetworkAgent na, @NonNull NetworkInfo ni,
3825 @NonNull LinkProperties lp, @NonNull NetworkCapabilities nc,
3826 @NonNull NetworkScore score, @NonNull NetworkAgentConfig config, int providerId) {
3827 return registerNetworkAgent(na, ni, lp, nc, null /* localNetworkConfig */, score, config,
3828 providerId);
3829 }
3830
3831 /**
3832 * @hide
3833 * Register a NetworkAgent with ConnectivityService.
3834 * @return Network corresponding to NetworkAgent.
3835 */
3836 @RequiresPermission(anyOf = {
3837 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3838 android.Manifest.permission.NETWORK_FACTORY})
3839 public Network registerNetworkAgent(@NonNull INetworkAgent na, @NonNull NetworkInfo ni,
3840 @NonNull LinkProperties lp, @NonNull NetworkCapabilities nc,
3841 @Nullable LocalNetworkConfig localNetworkConfig, @NonNull NetworkScore score,
3842 @NonNull NetworkAgentConfig config, int providerId) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003843 try {
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09003844 return mService.registerNetworkAgent(na, ni, lp, nc, score, localNetworkConfig, config,
3845 providerId);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003846 } catch (RemoteException e) {
3847 throw e.rethrowFromSystemServer();
3848 }
3849 }
3850
3851 /**
3852 * Base class for {@code NetworkRequest} callbacks. Used for notifications about network
3853 * changes. Should be extended by applications wanting notifications.
3854 *
3855 * A {@code NetworkCallback} is registered by calling
3856 * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
3857 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)},
3858 * or {@link #registerDefaultNetworkCallback(NetworkCallback)}. A {@code NetworkCallback} is
3859 * unregistered by calling {@link #unregisterNetworkCallback(NetworkCallback)}.
3860 * A {@code NetworkCallback} should be registered at most once at any time.
3861 * A {@code NetworkCallback} that has been unregistered can be registered again.
3862 */
3863 public static class NetworkCallback {
3864 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08003865 * No flags associated with this callback.
3866 * @hide
3867 */
3868 public static final int FLAG_NONE = 0;
lucaslinc582d502022-01-27 09:07:00 +08003869
Roshan Piuse08bc182020-12-22 15:10:42 -08003870 /**
lucaslinc582d502022-01-27 09:07:00 +08003871 * Inclusion of this flag means location-sensitive redaction requests keeping location info.
3872 *
3873 * Some objects like {@link NetworkCapabilities} may contain location-sensitive information.
3874 * Prior to Android 12, this information is always returned to apps holding the appropriate
3875 * permission, possibly noting that the app has used location.
3876 * <p>In Android 12 and above, by default the sent objects do not contain any location
3877 * information, even if the app holds the necessary permissions, and the system does not
3878 * take note of location usage by the app. Apps can request that location information is
3879 * included, in which case the system will check location permission and the location
3880 * toggle state, and take note of location usage by the app if any such information is
3881 * returned.
3882 *
Roshan Piuse08bc182020-12-22 15:10:42 -08003883 * Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
3884 * via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
3885 * <p>
3886 * These include:
3887 * <li> Some transport info instances (retrieved via
3888 * {@link NetworkCapabilities#getTransportInfo()}) like {@link android.net.wifi.WifiInfo}
3889 * contain location sensitive information.
3890 * <li> OwnerUid (retrieved via {@link NetworkCapabilities#getOwnerUid()} is location
Anton Hanssondf401092021-10-20 11:27:13 +01003891 * sensitive for wifi suggestor apps (i.e using
3892 * {@link android.net.wifi.WifiNetworkSuggestion WifiNetworkSuggestion}).</li>
Roshan Piuse08bc182020-12-22 15:10:42 -08003893 * </p>
3894 * <p>
3895 * Note:
3896 * <li> Retrieving this location sensitive information (subject to app's location
3897 * permissions) will be noted by system. </li>
3898 * <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
lucaslinc582d502022-01-27 09:07:00 +08003899 * not include location sensitive information.
Roshan Piuse08bc182020-12-22 15:10:42 -08003900 */
Roshan Pius189d0092021-03-11 21:16:44 -08003901 // Note: Some existing fields which are location sensitive may still be included without
3902 // this flag if the app targets SDK < S (to maintain backwards compatibility).
Roshan Piuse08bc182020-12-22 15:10:42 -08003903 public static final int FLAG_INCLUDE_LOCATION_INFO = 1 << 0;
3904
3905 /** @hide */
3906 @Retention(RetentionPolicy.SOURCE)
3907 @IntDef(flag = true, prefix = "FLAG_", value = {
3908 FLAG_NONE,
3909 FLAG_INCLUDE_LOCATION_INFO
3910 })
3911 public @interface Flag { }
3912
3913 /**
3914 * All the valid flags for error checking.
3915 */
3916 private static final int VALID_FLAGS = FLAG_INCLUDE_LOCATION_INFO;
3917
3918 public NetworkCallback() {
3919 this(FLAG_NONE);
3920 }
3921
3922 public NetworkCallback(@Flag int flags) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00003923 if ((flags & VALID_FLAGS) != flags) {
3924 throw new IllegalArgumentException("Invalid flags");
3925 }
Roshan Piuse08bc182020-12-22 15:10:42 -08003926 mFlags = flags;
3927 }
3928
3929 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003930 * Called when the framework connects to a new network to evaluate whether it satisfies this
3931 * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
3932 * callback. There is no guarantee that this new network will satisfy any requests, or that
3933 * the network will stay connected for longer than the time necessary to evaluate it.
3934 * <p>
3935 * Most applications <b>should not</b> act on this callback, and should instead use
3936 * {@link #onAvailable}. This callback is intended for use by applications that can assist
3937 * the framework in properly evaluating the network &mdash; for example, an application that
3938 * can automatically log in to a captive portal without user intervention.
3939 *
3940 * @param network The {@link Network} of the network that is being evaluated.
3941 *
3942 * @hide
3943 */
3944 public void onPreCheck(@NonNull Network network) {}
3945
3946 /**
3947 * Called when the framework connects and has declared a new network ready for use.
3948 * This callback may be called more than once if the {@link Network} that is
3949 * satisfying the request changes.
3950 *
3951 * @param network The {@link Network} of the satisfying network.
3952 * @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
3953 * @param linkProperties The {@link LinkProperties} of the satisfying network.
3954 * @param blocked Whether access to the {@link Network} is blocked due to system policy.
3955 * @hide
3956 */
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003957 public final void onAvailable(@NonNull Network network,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003958 @NonNull NetworkCapabilities networkCapabilities,
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003959 @NonNull LinkProperties linkProperties, @BlockedReason int blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003960 // Internally only this method is called when a new network is available, and
3961 // it calls the callback in the same way and order that older versions used
3962 // to call so as not to change the behavior.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003963 onAvailable(network, networkCapabilities, linkProperties, blocked != 0);
3964 onBlockedStatusChanged(network, blocked);
3965 }
3966
3967 /**
3968 * Legacy variant of onAvailable that takes a boolean blocked reason.
3969 *
3970 * This method has never been public API, but it's not final, so there may be apps that
3971 * implemented it and rely on it being called. Do our best not to break them.
3972 * Note: such apps will also get a second call to onBlockedStatusChanged immediately after
3973 * this method is called. There does not seem to be a way to avoid this.
3974 * TODO: add a compat check to move apps off this method, and eventually stop calling it.
3975 *
3976 * @hide
3977 */
3978 public void onAvailable(@NonNull Network network,
3979 @NonNull NetworkCapabilities networkCapabilities,
3980 @NonNull LinkProperties linkProperties, boolean blocked) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003981 onAvailable(network);
3982 if (!networkCapabilities.hasCapability(
3983 NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
3984 onNetworkSuspended(network);
3985 }
3986 onCapabilitiesChanged(network, networkCapabilities);
3987 onLinkPropertiesChanged(network, linkProperties);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09003988 // No call to onBlockedStatusChanged here. That is done by the caller.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09003989 }
3990
3991 /**
3992 * Called when the framework connects and has declared a new network ready for use.
3993 *
3994 * <p>For callbacks registered with {@link #registerNetworkCallback}, multiple networks may
3995 * be available at the same time, and onAvailable will be called for each of these as they
3996 * appear.
3997 *
3998 * <p>For callbacks registered with {@link #requestNetwork} and
3999 * {@link #registerDefaultNetworkCallback}, this means the network passed as an argument
4000 * is the new best network for this request and is now tracked by this callback ; this
4001 * callback will no longer receive method calls about other networks that may have been
4002 * passed to this method previously. The previously-best network may have disconnected, or
4003 * it may still be around and the newly-best network may simply be better.
4004 *
4005 * <p>Starting with {@link android.os.Build.VERSION_CODES#O}, this will always immediately
4006 * be followed by a call to {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}
4007 * then by a call to {@link #onLinkPropertiesChanged(Network, LinkProperties)}, and a call
4008 * to {@link #onBlockedStatusChanged(Network, boolean)}.
4009 *
4010 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4011 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4012 * this callback as this is prone to race conditions (there is no guarantee the objects
4013 * returned by these methods will be current). Instead, wait for a call to
4014 * {@link #onCapabilitiesChanged(Network, NetworkCapabilities)} and
4015 * {@link #onLinkPropertiesChanged(Network, LinkProperties)} whose arguments are guaranteed
4016 * to be well-ordered with respect to other callbacks.
4017 *
4018 * @param network The {@link Network} of the satisfying network.
4019 */
4020 public void onAvailable(@NonNull Network network) {}
4021
4022 /**
4023 * Called when the network is about to be lost, typically because there are no outstanding
4024 * requests left for it. This may be paired with a {@link NetworkCallback#onAvailable} call
4025 * with the new replacement network for graceful handover. This method is not guaranteed
4026 * to be called before {@link NetworkCallback#onLost} is called, for example in case a
4027 * network is suddenly disconnected.
4028 *
4029 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4030 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4031 * this callback as this is prone to race conditions ; calling these methods while in a
4032 * callback may return an outdated or even a null object.
4033 *
4034 * @param network The {@link Network} that is about to be lost.
4035 * @param maxMsToLive The time in milliseconds the system intends to keep the network
4036 * connected for graceful handover; note that the network may still
4037 * suffer a hard loss at any time.
4038 */
4039 public void onLosing(@NonNull Network network, int maxMsToLive) {}
4040
4041 /**
4042 * Called when a network disconnects or otherwise no longer satisfies this request or
4043 * callback.
4044 *
4045 * <p>If the callback was registered with requestNetwork() or
4046 * registerDefaultNetworkCallback(), it will only be invoked against the last network
4047 * returned by onAvailable() when that network is lost and no other network satisfies
4048 * the criteria of the request.
4049 *
4050 * <p>If the callback was registered with registerNetworkCallback() it will be called for
4051 * each network which no longer satisfies the criteria of the callback.
4052 *
4053 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4054 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4055 * this callback as this is prone to race conditions ; calling these methods while in a
4056 * callback may return an outdated or even a null object.
4057 *
4058 * @param network The {@link Network} lost.
4059 */
4060 public void onLost(@NonNull Network network) {}
4061
4062 /**
4063 * Called if no network is found within the timeout time specified in
4064 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} call or if the
4065 * requested network request cannot be fulfilled (whether or not a timeout was
4066 * specified). When this callback is invoked the associated
4067 * {@link NetworkRequest} will have already been removed and released, as if
4068 * {@link #unregisterNetworkCallback(NetworkCallback)} had been called.
4069 */
4070 public void onUnavailable() {}
4071
4072 /**
4073 * Called when the network corresponding to this request changes capabilities but still
4074 * satisfies the requested criteria.
4075 *
4076 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
4077 * to be called immediately after {@link #onAvailable}.
4078 *
4079 * <p>Do NOT call {@link #getLinkProperties(Network)} or other synchronous
4080 * ConnectivityManager methods in this callback as this is prone to race conditions :
4081 * calling these methods while in a callback may return an outdated or even a null object.
4082 *
4083 * @param network The {@link Network} whose capabilities have changed.
Roshan Piuse08bc182020-12-22 15:10:42 -08004084 * @param networkCapabilities The new {@link NetworkCapabilities} for this
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004085 * network.
4086 */
4087 public void onCapabilitiesChanged(@NonNull Network network,
4088 @NonNull NetworkCapabilities networkCapabilities) {}
4089
4090 /**
4091 * Called when the network corresponding to this request changes {@link LinkProperties}.
4092 *
4093 * <p>Starting with {@link android.os.Build.VERSION_CODES#O} this method is guaranteed
4094 * to be called immediately after {@link #onAvailable}.
4095 *
4096 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or other synchronous
4097 * ConnectivityManager methods in this callback as this is prone to race conditions :
4098 * calling these methods while in a callback may return an outdated or even a null object.
4099 *
4100 * @param network The {@link Network} whose link properties have changed.
4101 * @param linkProperties The new {@link LinkProperties} for this network.
4102 */
4103 public void onLinkPropertiesChanged(@NonNull Network network,
4104 @NonNull LinkProperties linkProperties) {}
4105
4106 /**
4107 * Called when the network the framework connected to for this request suspends data
4108 * transmission temporarily.
4109 *
4110 * <p>This generally means that while the TCP connections are still live temporarily
4111 * network data fails to transfer. To give a specific example, this is used on cellular
4112 * networks to mask temporary outages when driving through a tunnel, etc. In general this
4113 * means read operations on sockets on this network will block once the buffers are
4114 * drained, and write operations will block once the buffers are full.
4115 *
4116 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4117 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4118 * this callback as this is prone to race conditions (there is no guarantee the objects
4119 * returned by these methods will be current).
4120 *
4121 * @hide
4122 */
4123 public void onNetworkSuspended(@NonNull Network network) {}
4124
4125 /**
4126 * Called when the network the framework connected to for this request
4127 * returns from a {@link NetworkInfo.State#SUSPENDED} state. This should always be
4128 * preceded by a matching {@link NetworkCallback#onNetworkSuspended} call.
4129
4130 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4131 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4132 * this callback as this is prone to race conditions : calling these methods while in a
4133 * callback may return an outdated or even a null object.
4134 *
4135 * @hide
4136 */
4137 public void onNetworkResumed(@NonNull Network network) {}
4138
4139 /**
4140 * Called when access to the specified network is blocked or unblocked.
4141 *
4142 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4143 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4144 * this callback as this is prone to race conditions : calling these methods while in a
4145 * callback may return an outdated or even a null object.
4146 *
4147 * @param network The {@link Network} whose blocked status has changed.
4148 * @param blocked The blocked status of this {@link Network}.
4149 */
4150 public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) {}
4151
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004152 /**
Lorenzo Colittia1bd6f62021-03-25 23:17:36 +09004153 * Called when access to the specified network is blocked or unblocked, or the reason for
4154 * access being blocked changes.
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004155 *
4156 * If a NetworkCallback object implements this method,
4157 * {@link #onBlockedStatusChanged(Network, boolean)} will not be called.
4158 *
4159 * <p>Do NOT call {@link #getNetworkCapabilities(Network)} or
4160 * {@link #getLinkProperties(Network)} or other synchronous ConnectivityManager methods in
4161 * this callback as this is prone to race conditions : calling these methods while in a
4162 * callback may return an outdated or even a null object.
4163 *
4164 * @param network The {@link Network} whose blocked status has changed.
4165 * @param blocked The blocked status of this {@link Network}.
4166 * @hide
4167 */
4168 @SystemApi(client = MODULE_LIBRARIES)
4169 public void onBlockedStatusChanged(@NonNull Network network, @BlockedReason int blocked) {
4170 onBlockedStatusChanged(network, blocked != 0);
4171 }
4172
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004173 private NetworkRequest networkRequest;
Roshan Piuse08bc182020-12-22 15:10:42 -08004174 private final int mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004175 }
4176
4177 /**
4178 * Constant error codes used by ConnectivityService to communicate about failures and errors
4179 * across a Binder boundary.
4180 * @hide
4181 */
4182 public interface Errors {
4183 int TOO_MANY_REQUESTS = 1;
4184 }
4185
4186 /** @hide */
4187 public static class TooManyRequestsException extends RuntimeException {}
4188
4189 private static RuntimeException convertServiceException(ServiceSpecificException e) {
4190 switch (e.errorCode) {
4191 case Errors.TOO_MANY_REQUESTS:
4192 return new TooManyRequestsException();
4193 default:
4194 Log.w(TAG, "Unknown service error code " + e.errorCode);
4195 return new RuntimeException(e);
4196 }
4197 }
4198
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004199 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004200 public static final int CALLBACK_PRECHECK = 1;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004201 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004202 public static final int CALLBACK_AVAILABLE = 2;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004203 /** @hide arg1 = TTL */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004204 public static final int CALLBACK_LOSING = 3;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004205 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004206 public static final int CALLBACK_LOST = 4;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004207 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004208 public static final int CALLBACK_UNAVAIL = 5;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004209 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004210 public static final int CALLBACK_CAP_CHANGED = 6;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004211 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004212 public static final int CALLBACK_IP_CHANGED = 7;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004213 /** @hide obj = NetworkCapabilities, arg1 = seq number */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004214 private static final int EXPIRE_LEGACY_REQUEST = 8;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004215 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004216 public static final int CALLBACK_SUSPENDED = 9;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004217 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004218 public static final int CALLBACK_RESUMED = 10;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004219 /** @hide */
Remi NGUYEN VAN1b9f03a2021-03-12 15:24:06 +09004220 public static final int CALLBACK_BLK_CHANGED = 11;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004221
4222 /** @hide */
4223 public static String getCallbackName(int whichCallback) {
4224 switch (whichCallback) {
4225 case CALLBACK_PRECHECK: return "CALLBACK_PRECHECK";
4226 case CALLBACK_AVAILABLE: return "CALLBACK_AVAILABLE";
4227 case CALLBACK_LOSING: return "CALLBACK_LOSING";
4228 case CALLBACK_LOST: return "CALLBACK_LOST";
4229 case CALLBACK_UNAVAIL: return "CALLBACK_UNAVAIL";
4230 case CALLBACK_CAP_CHANGED: return "CALLBACK_CAP_CHANGED";
4231 case CALLBACK_IP_CHANGED: return "CALLBACK_IP_CHANGED";
4232 case EXPIRE_LEGACY_REQUEST: return "EXPIRE_LEGACY_REQUEST";
4233 case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
4234 case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
4235 case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
4236 default:
4237 return Integer.toString(whichCallback);
4238 }
4239 }
4240
zhujiatai79b0de92022-09-22 15:44:02 +08004241 private static class CallbackHandler extends Handler {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004242 private static final String TAG = "ConnectivityManager.CallbackHandler";
4243 private static final boolean DBG = false;
4244
4245 CallbackHandler(Looper looper) {
4246 super(looper);
4247 }
4248
4249 CallbackHandler(Handler handler) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004250 this(Objects.requireNonNull(handler, "Handler cannot be null.").getLooper());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004251 }
4252
4253 @Override
4254 public void handleMessage(Message message) {
4255 if (message.what == EXPIRE_LEGACY_REQUEST) {
zhujiatai79b0de92022-09-22 15:44:02 +08004256 // the sInstance can't be null because to send this message a ConnectivityManager
4257 // instance must have been created prior to creating the thread on which this
4258 // Handler is running.
4259 sInstance.expireRequest((NetworkCapabilities) message.obj, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004260 return;
4261 }
4262
4263 final NetworkRequest request = getObject(message, NetworkRequest.class);
4264 final Network network = getObject(message, Network.class);
4265 final NetworkCallback callback;
4266 synchronized (sCallbacks) {
4267 callback = sCallbacks.get(request);
4268 if (callback == null) {
4269 Log.w(TAG,
4270 "callback not found for " + getCallbackName(message.what) + " message");
4271 return;
4272 }
4273 if (message.what == CALLBACK_UNAVAIL) {
4274 sCallbacks.remove(request);
4275 callback.networkRequest = ALREADY_UNREGISTERED;
4276 }
4277 }
4278 if (DBG) {
4279 Log.d(TAG, getCallbackName(message.what) + " for network " + network);
4280 }
4281
4282 switch (message.what) {
4283 case CALLBACK_PRECHECK: {
4284 callback.onPreCheck(network);
4285 break;
4286 }
4287 case CALLBACK_AVAILABLE: {
4288 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
4289 LinkProperties lp = getObject(message, LinkProperties.class);
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004290 callback.onAvailable(network, cap, lp, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004291 break;
4292 }
4293 case CALLBACK_LOSING: {
4294 callback.onLosing(network, message.arg1);
4295 break;
4296 }
4297 case CALLBACK_LOST: {
4298 callback.onLost(network);
4299 break;
4300 }
4301 case CALLBACK_UNAVAIL: {
4302 callback.onUnavailable();
4303 break;
4304 }
4305 case CALLBACK_CAP_CHANGED: {
4306 NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
4307 callback.onCapabilitiesChanged(network, cap);
4308 break;
4309 }
4310 case CALLBACK_IP_CHANGED: {
4311 LinkProperties lp = getObject(message, LinkProperties.class);
4312 callback.onLinkPropertiesChanged(network, lp);
4313 break;
4314 }
4315 case CALLBACK_SUSPENDED: {
4316 callback.onNetworkSuspended(network);
4317 break;
4318 }
4319 case CALLBACK_RESUMED: {
4320 callback.onNetworkResumed(network);
4321 break;
4322 }
4323 case CALLBACK_BLK_CHANGED: {
Lorenzo Colitti8ad58122021-03-18 00:54:57 +09004324 callback.onBlockedStatusChanged(network, message.arg1);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004325 }
4326 }
4327 }
4328
4329 private <T> T getObject(Message msg, Class<T> c) {
4330 return (T) msg.getData().getParcelable(c.getSimpleName());
4331 }
4332 }
4333
4334 private CallbackHandler getDefaultHandler() {
4335 synchronized (sCallbacks) {
4336 if (sCallbackHandler == null) {
4337 sCallbackHandler = new CallbackHandler(ConnectivityThread.getInstanceLooper());
4338 }
4339 return sCallbackHandler;
4340 }
4341 }
4342
4343 private static final HashMap<NetworkRequest, NetworkCallback> sCallbacks = new HashMap<>();
4344 private static CallbackHandler sCallbackHandler;
4345
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004346 private NetworkRequest sendRequestForNetwork(int asUid, NetworkCapabilities need,
4347 NetworkCallback callback, int timeoutMs, NetworkRequest.Type reqType, int legacyType,
4348 CallbackHandler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004349 printStackTrace();
4350 checkCallbackNotNull(callback);
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004351 if (reqType != TRACK_DEFAULT && reqType != TRACK_SYSTEM_DEFAULT && need == null) {
4352 throw new IllegalArgumentException("null NetworkCapabilities");
4353 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004354 final NetworkRequest request;
4355 final String callingPackageName = mContext.getOpPackageName();
4356 try {
4357 synchronized(sCallbacks) {
4358 if (callback.networkRequest != null
4359 && callback.networkRequest != ALREADY_UNREGISTERED) {
4360 // TODO: throw exception instead and enforce 1:1 mapping of callbacks
4361 // and requests (http://b/20701525).
4362 Log.e(TAG, "NetworkCallback was already registered");
4363 }
4364 Messenger messenger = new Messenger(handler);
4365 Binder binder = new Binder();
Roshan Piuse08bc182020-12-22 15:10:42 -08004366 final int callbackFlags = callback.mFlags;
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004367 if (reqType == LISTEN) {
4368 request = mService.listenForNetwork(
Roshan Piuse08bc182020-12-22 15:10:42 -08004369 need, messenger, binder, callbackFlags, callingPackageName,
Roshan Piusa8a477b2020-12-17 14:53:09 -08004370 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004371 } else {
4372 request = mService.requestNetwork(
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004373 asUid, need, reqType.ordinal(), messenger, timeoutMs, binder,
4374 legacyType, callbackFlags, callingPackageName, getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004375 }
4376 if (request != null) {
4377 sCallbacks.put(request, callback);
4378 }
4379 callback.networkRequest = request;
4380 }
4381 } catch (RemoteException e) {
4382 throw e.rethrowFromSystemServer();
4383 } catch (ServiceSpecificException e) {
4384 throw convertServiceException(e);
4385 }
4386 return request;
4387 }
4388
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004389 private NetworkRequest sendRequestForNetwork(NetworkCapabilities need, NetworkCallback callback,
4390 int timeoutMs, NetworkRequest.Type reqType, int legacyType, CallbackHandler handler) {
4391 return sendRequestForNetwork(Process.INVALID_UID, need, callback, timeoutMs, reqType,
4392 legacyType, handler);
4393 }
4394
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004395 /**
4396 * Helper function to request a network with a particular legacy type.
4397 *
4398 * This API is only for use in internal system code that requests networks with legacy type and
4399 * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
4400 * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
4401 *
4402 * @param request {@link NetworkRequest} describing this request.
4403 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4404 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4405 * be a positive value (i.e. >0).
4406 * @param legacyType to specify the network type(#TYPE_*).
4407 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4408 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4409 * the callback must not be shared - it uniquely specifies this request.
4410 *
4411 * @hide
4412 */
4413 @SystemApi
4414 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4415 public void requestNetwork(@NonNull NetworkRequest request,
4416 int timeoutMs, int legacyType, @NonNull Handler handler,
4417 @NonNull NetworkCallback networkCallback) {
4418 if (legacyType == TYPE_NONE) {
4419 throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
4420 }
4421 CallbackHandler cbHandler = new CallbackHandler(handler);
4422 NetworkCapabilities nc = request.networkCapabilities;
4423 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
4424 }
4425
4426 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004427 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004428 *
4429 * <p>This method will attempt to find the best network that matches the passed
4430 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
4431 * criteria. The platform will evaluate which network is the best at its own discretion.
4432 * Throughput, latency, cost per byte, policy, user preference and other considerations
4433 * may be factored in the decision of what is considered the best network.
4434 *
4435 * <p>As long as this request is outstanding, the platform will try to maintain the best network
4436 * matching this request, while always attempting to match the request to a better network if
4437 * possible. If a better match is found, the platform will switch this request to the now-best
4438 * network and inform the app of the newly best network by invoking
4439 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
4440 * will not try to maintain any other network than the best one currently matching the request:
4441 * a network not matching any network request may be disconnected at any time.
4442 *
4443 * <p>For example, an application could use this method to obtain a connected cellular network
4444 * even if the device currently has a data connection over Ethernet. This may cause the cellular
4445 * radio to consume additional power. Or, an application could inform the system that it wants
4446 * a network supporting sending MMSes and have the system let it know about the currently best
4447 * MMS-supporting network through the provided {@link NetworkCallback}.
4448 *
4449 * <p>The status of the request can be followed by listening to the various callbacks described
4450 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
4451 * used to direct traffic to the network (although accessing some networks may be subject to
4452 * holding specific permissions). Callers will learn about the specific characteristics of the
4453 * network through
4454 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
4455 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
4456 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
4457 * matching the request at any given time; therefore when a better network matching the request
4458 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
4459 * with the new network after which no further updates are given about the previously-best
4460 * network, unless it becomes the best again at some later time. All callbacks are invoked
4461 * in order on the same thread, which by default is a thread created by the framework running
4462 * in the app.
chiachangwang9473c592022-07-15 02:25:52 +00004463 * See {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004464 * callbacks are invoked.
4465 *
4466 * <p>This{@link NetworkRequest} will live until released via
4467 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
4468 * which point the system may let go of the network at any time.
4469 *
4470 * <p>A version of this method which takes a timeout is
4471 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
4472 * wait for a limited amount of time for the network to become unavailable.
4473 *
4474 * <p>It is presently unsupported to request a network with mutable
4475 * {@link NetworkCapabilities} such as
4476 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4477 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4478 * as these {@code NetworkCapabilities} represent states that a particular
4479 * network may never attain, and whether a network will attain these states
4480 * is unknown prior to bringing up the network so the framework does not
4481 * know how to go about satisfying a request with these capabilities.
4482 *
4483 * <p>This method requires the caller to hold either the
4484 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4485 * or the ability to modify system settings as determined by
4486 * {@link android.provider.Settings.System#canWrite}.</p>
4487 *
4488 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4489 * number of outstanding requests to 100 per app (identified by their UID), shared with
4490 * all variants of this method, of {@link #registerNetworkCallback} as well as
4491 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4492 * Requesting a network with this method will count toward this limit. If this limit is
4493 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4494 * make sure to unregister the callbacks with
4495 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4496 *
4497 * @param request {@link NetworkRequest} describing this request.
4498 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4499 * the callback must not be shared - it uniquely specifies this request.
4500 * The callback is invoked on the default internal Handler.
4501 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4502 * @throws SecurityException if missing the appropriate permissions.
4503 * @throws RuntimeException if the app already has too many callbacks registered.
4504 */
4505 public void requestNetwork(@NonNull NetworkRequest request,
4506 @NonNull NetworkCallback networkCallback) {
4507 requestNetwork(request, networkCallback, getDefaultHandler());
4508 }
4509
4510 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004511 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004512 *
4513 * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
4514 * but runs all the callbacks on the passed Handler.
4515 *
4516 * <p>This method has the same permission requirements as
4517 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4518 * and throws the same exceptions in the same conditions.
4519 *
4520 * @param request {@link NetworkRequest} describing this request.
4521 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4522 * the callback must not be shared - it uniquely specifies this request.
4523 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4524 */
4525 public void requestNetwork(@NonNull NetworkRequest request,
4526 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4527 CallbackHandler cbHandler = new CallbackHandler(handler);
4528 NetworkCapabilities nc = request.networkCapabilities;
4529 sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
4530 }
4531
4532 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004533 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004534 * by a timeout.
4535 *
4536 * This function behaves identically to the non-timed-out version
4537 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
4538 * is not found within the given time (in milliseconds) the
4539 * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
4540 * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
4541 * not have to be released if timed-out (it is automatically released). Unregistering a
4542 * request that timed out is not an error.
4543 *
4544 * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
4545 * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
4546 * for that purpose. Calling this method will attempt to bring up the requested network.
4547 *
4548 * <p>This method has the same permission requirements as
4549 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4550 * and throws the same exceptions in the same conditions.
4551 *
4552 * @param request {@link NetworkRequest} describing this request.
4553 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4554 * the callback must not be shared - it uniquely specifies this request.
4555 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4556 * before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4557 * be a positive value (i.e. >0).
4558 */
4559 public void requestNetwork(@NonNull NetworkRequest request,
4560 @NonNull NetworkCallback networkCallback, int timeoutMs) {
4561 checkTimeout(timeoutMs);
4562 NetworkCapabilities nc = request.networkCapabilities;
4563 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
4564 getDefaultHandler());
4565 }
4566
4567 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004568 * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004569 * by a timeout.
4570 *
4571 * This method behaves identically to
4572 * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
4573 * on the passed Handler.
4574 *
4575 * <p>This method has the same permission requirements as
4576 * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4577 * and throws the same exceptions in the same conditions.
4578 *
4579 * @param request {@link NetworkRequest} describing this request.
4580 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4581 * the callback must not be shared - it uniquely specifies this request.
4582 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4583 * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4584 * before {@link NetworkCallback#onUnavailable} is called.
4585 */
4586 public void requestNetwork(@NonNull NetworkRequest request,
4587 @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
4588 checkTimeout(timeoutMs);
4589 CallbackHandler cbHandler = new CallbackHandler(handler);
4590 NetworkCapabilities nc = request.networkCapabilities;
4591 sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
4592 }
4593
4594 /**
4595 * The lookup key for a {@link Network} object included with the intent after
4596 * successfully finding a network for the applications request. Retrieve it with
4597 * {@link android.content.Intent#getParcelableExtra(String)}.
4598 * <p>
4599 * Note that if you intend to invoke {@link Network#openConnection(java.net.URL)}
4600 * then you must get a ConnectivityManager instance before doing so.
4601 */
4602 public static final String EXTRA_NETWORK = "android.net.extra.NETWORK";
4603
4604 /**
4605 * The lookup key for a {@link NetworkRequest} object included with the intent after
4606 * successfully finding a network for the applications request. Retrieve it with
4607 * {@link android.content.Intent#getParcelableExtra(String)}.
4608 */
4609 public static final String EXTRA_NETWORK_REQUEST = "android.net.extra.NETWORK_REQUEST";
4610
4611
4612 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08004613 * Request a network to satisfy a set of {@link NetworkCapabilities}.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004614 *
4615 * This function behaves identically to the version that takes a NetworkCallback, but instead
4616 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4617 * the request may outlive the calling application and get called back when a suitable
4618 * network is found.
4619 * <p>
4620 * The operation is an Intent broadcast that goes to a broadcast receiver that
4621 * you registered with {@link Context#registerReceiver} or through the
4622 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4623 * <p>
4624 * The operation Intent is delivered with two extras, a {@link Network} typed
4625 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4626 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4627 * the original requests parameters. It is important to create a new,
4628 * {@link NetworkCallback} based request before completing the processing of the
4629 * Intent to reserve the network or it will be released shortly after the Intent
4630 * is processed.
4631 * <p>
4632 * If there is already a request for this Intent registered (with the equality of
4633 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4634 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4635 * <p>
4636 * The request may be released normally by calling
4637 * {@link #releaseNetworkRequest(android.app.PendingIntent)}.
4638 * <p>It is presently unsupported to request a network with either
4639 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4640 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4641 * as these {@code NetworkCapabilities} represent states that a particular
4642 * network may never attain, and whether a network will attain these states
4643 * is unknown prior to bringing up the network so the framework does not
4644 * know how to go about satisfying a request with these capabilities.
4645 *
4646 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4647 * number of outstanding requests to 100 per app (identified by their UID), shared with
4648 * all variants of this method, of {@link #registerNetworkCallback} as well as
4649 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4650 * Requesting a network with this method will count toward this limit. If this limit is
4651 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4652 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4653 * or {@link #releaseNetworkRequest(PendingIntent)}.
4654 *
4655 * <p>This method requires the caller to hold either the
4656 * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4657 * or the ability to modify system settings as determined by
4658 * {@link android.provider.Settings.System#canWrite}.</p>
4659 *
4660 * @param request {@link NetworkRequest} describing this request.
4661 * @param operation Action to perform when the network is available (corresponds
4662 * to the {@link NetworkCallback#onAvailable} call. Typically
4663 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4664 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4665 * @throws SecurityException if missing the appropriate permissions.
4666 * @throws RuntimeException if the app already has too many callbacks registered.
4667 */
4668 public void requestNetwork(@NonNull NetworkRequest request,
4669 @NonNull PendingIntent operation) {
4670 printStackTrace();
4671 checkPendingIntentNotNull(operation);
4672 try {
4673 mService.pendingRequestForNetwork(
4674 request.networkCapabilities, operation, mContext.getOpPackageName(),
4675 getAttributionTag());
4676 } catch (RemoteException e) {
4677 throw e.rethrowFromSystemServer();
4678 } catch (ServiceSpecificException e) {
4679 throw convertServiceException(e);
4680 }
4681 }
4682
4683 /**
4684 * Removes a request made via {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)}
4685 * <p>
4686 * This method has the same behavior as
4687 * {@link #unregisterNetworkCallback(android.app.PendingIntent)} with respect to
4688 * releasing network resources and disconnecting.
4689 *
4690 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
4691 * PendingIntent passed to
4692 * {@link #requestNetwork(NetworkRequest, android.app.PendingIntent)} with the
4693 * corresponding NetworkRequest you'd like to remove. Cannot be null.
4694 */
4695 public void releaseNetworkRequest(@NonNull PendingIntent operation) {
4696 printStackTrace();
4697 checkPendingIntentNotNull(operation);
4698 try {
4699 mService.releasePendingNetworkRequest(operation);
4700 } catch (RemoteException e) {
4701 throw e.rethrowFromSystemServer();
4702 }
4703 }
4704
4705 private static void checkPendingIntentNotNull(PendingIntent intent) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004706 Objects.requireNonNull(intent, "PendingIntent cannot be null.");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004707 }
4708
4709 private static void checkCallbackNotNull(NetworkCallback callback) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004710 Objects.requireNonNull(callback, "null NetworkCallback");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004711 }
4712
4713 private static void checkTimeout(int timeoutMs) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00004714 if (timeoutMs <= 0) {
4715 throw new IllegalArgumentException("timeoutMs must be strictly positive.");
4716 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004717 }
4718
4719 /**
4720 * Registers to receive notifications about all networks which satisfy the given
4721 * {@link NetworkRequest}. The callbacks will continue to be called until
4722 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4723 * called.
4724 *
4725 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4726 * number of outstanding requests to 100 per app (identified by their UID), shared with
4727 * all variants of this method, of {@link #requestNetwork} as well as
4728 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4729 * Requesting a network with this method will count toward this limit. If this limit is
4730 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4731 * make sure to unregister the callbacks with
4732 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4733 *
4734 * @param request {@link NetworkRequest} describing this request.
4735 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4736 * networks change state.
4737 * The callback is invoked on the default internal Handler.
4738 * @throws RuntimeException if the app already has too many callbacks registered.
4739 */
4740 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4741 public void registerNetworkCallback(@NonNull NetworkRequest request,
4742 @NonNull NetworkCallback networkCallback) {
4743 registerNetworkCallback(request, networkCallback, getDefaultHandler());
4744 }
4745
4746 /**
4747 * Registers to receive notifications about all networks which satisfy the given
4748 * {@link NetworkRequest}. The callbacks will continue to be called until
4749 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4750 * called.
4751 *
4752 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4753 * number of outstanding requests to 100 per app (identified by their UID), shared with
4754 * all variants of this method, of {@link #requestNetwork} as well as
4755 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4756 * Requesting a network with this method will count toward this limit. If this limit is
4757 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4758 * make sure to unregister the callbacks with
4759 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4760 *
4761 *
4762 * @param request {@link NetworkRequest} describing this request.
4763 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4764 * networks change state.
4765 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4766 * @throws RuntimeException if the app already has too many callbacks registered.
4767 */
4768 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4769 public void registerNetworkCallback(@NonNull NetworkRequest request,
4770 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4771 CallbackHandler cbHandler = new CallbackHandler(handler);
4772 NetworkCapabilities nc = request.networkCapabilities;
4773 sendRequestForNetwork(nc, networkCallback, 0, LISTEN, TYPE_NONE, cbHandler);
4774 }
4775
4776 /**
4777 * Registers a PendingIntent to be sent when a network is available which satisfies the given
4778 * {@link NetworkRequest}.
4779 *
4780 * This function behaves identically to the version that takes a NetworkCallback, but instead
4781 * of {@link NetworkCallback} a {@link PendingIntent} is used. This means
4782 * the request may outlive the calling application and get called back when a suitable
4783 * network is found.
4784 * <p>
4785 * The operation is an Intent broadcast that goes to a broadcast receiver that
4786 * you registered with {@link Context#registerReceiver} or through the
4787 * &lt;receiver&gt; tag in an AndroidManifest.xml file
4788 * <p>
4789 * The operation Intent is delivered with two extras, a {@link Network} typed
4790 * extra called {@link #EXTRA_NETWORK} and a {@link NetworkRequest}
4791 * typed extra called {@link #EXTRA_NETWORK_REQUEST} containing
4792 * the original requests parameters.
4793 * <p>
4794 * If there is already a request for this Intent registered (with the equality of
4795 * two Intents defined by {@link Intent#filterEquals}), then it will be removed and
4796 * replaced by this one, effectively releasing the previous {@link NetworkRequest}.
4797 * <p>
4798 * The request may be released normally by calling
4799 * {@link #unregisterNetworkCallback(android.app.PendingIntent)}.
4800 *
4801 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4802 * number of outstanding requests to 100 per app (identified by their UID), shared with
4803 * all variants of this method, of {@link #requestNetwork} as well as
4804 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4805 * Requesting a network with this method will count toward this limit. If this limit is
4806 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4807 * make sure to unregister the callbacks with {@link #unregisterNetworkCallback(PendingIntent)}
4808 * or {@link #releaseNetworkRequest(PendingIntent)}.
4809 *
4810 * @param request {@link NetworkRequest} describing this request.
4811 * @param operation Action to perform when the network is available (corresponds
4812 * to the {@link NetworkCallback#onAvailable} call. Typically
4813 * comes from {@link PendingIntent#getBroadcast}. Cannot be null.
4814 * @throws RuntimeException if the app already has too many callbacks registered.
4815 */
4816 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4817 public void registerNetworkCallback(@NonNull NetworkRequest request,
4818 @NonNull PendingIntent operation) {
4819 printStackTrace();
4820 checkPendingIntentNotNull(operation);
4821 try {
4822 mService.pendingListenForNetwork(
Roshan Piusa8a477b2020-12-17 14:53:09 -08004823 request.networkCapabilities, operation, mContext.getOpPackageName(),
4824 getAttributionTag());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004825 } catch (RemoteException e) {
4826 throw e.rethrowFromSystemServer();
4827 } catch (ServiceSpecificException e) {
4828 throw convertServiceException(e);
4829 }
4830 }
4831
4832 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004833 * Registers to receive notifications about changes in the application's default network. This
4834 * may be a physical network or a virtual network, such as a VPN that applies to the
4835 * application. The callbacks will continue to be called until either the application exits or
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004836 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4837 *
4838 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4839 * number of outstanding requests to 100 per app (identified by their UID), shared with
4840 * all variants of this method, of {@link #requestNetwork} as well as
4841 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4842 * Requesting a network with this method will count toward this limit. If this limit is
4843 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4844 * make sure to unregister the callbacks with
4845 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4846 *
4847 * @param networkCallback The {@link NetworkCallback} that the system will call as the
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004848 * application's default network changes.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004849 * The callback is invoked on the default internal Handler.
4850 * @throws RuntimeException if the app already has too many callbacks registered.
4851 */
4852 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4853 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback) {
4854 registerDefaultNetworkCallback(networkCallback, getDefaultHandler());
4855 }
4856
4857 /**
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004858 * Registers to receive notifications about changes in the application's default network. This
4859 * may be a physical network or a virtual network, such as a VPN that applies to the
4860 * application. The callbacks will continue to be called until either the application exits or
4861 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4862 *
4863 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4864 * number of outstanding requests to 100 per app (identified by their UID), shared with
4865 * all variants of this method, of {@link #requestNetwork} as well as
4866 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4867 * Requesting a network with this method will count toward this limit. If this limit is
4868 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4869 * make sure to unregister the callbacks with
4870 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4871 *
4872 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4873 * application's default network changes.
4874 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4875 * @throws RuntimeException if the app already has too many callbacks registered.
4876 */
4877 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
4878 public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
4879 @NonNull Handler handler) {
Chiachang Wangc7d203d2021-04-20 15:41:24 +08004880 registerDefaultNetworkCallbackForUid(Process.INVALID_UID, networkCallback, handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004881 }
4882
4883 /**
4884 * Registers to receive notifications about changes in the default network for the specified
4885 * UID. This may be a physical network or a virtual network, such as a VPN that applies to the
4886 * UID. The callbacks will continue to be called until either the application exits or
4887 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4888 *
4889 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4890 * number of outstanding requests to 100 per app (identified by their UID), shared with
4891 * all variants of this method, of {@link #requestNetwork} as well as
4892 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4893 * Requesting a network with this method will count toward this limit. If this limit is
4894 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4895 * make sure to unregister the callbacks with
4896 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4897 *
4898 * @param uid the UID for which to track default network changes.
4899 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4900 * UID's default network changes.
4901 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4902 * @throws RuntimeException if the app already has too many callbacks registered.
4903 * @hide
4904 */
Lorenzo Colittib90bdbd2021-03-22 18:23:21 +09004905 @SystemApi(client = MODULE_LIBRARIES)
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004906 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4907 @RequiresPermission(anyOf = {
4908 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4909 android.Manifest.permission.NETWORK_SETTINGS})
Chiachang Wangc7d203d2021-04-20 15:41:24 +08004910 public void registerDefaultNetworkCallbackForUid(int uid,
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004911 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004912 CallbackHandler cbHandler = new CallbackHandler(handler);
Lorenzo Colitti5f26b192021-03-12 22:48:07 +09004913 sendRequestForNetwork(uid, null /* need */, networkCallback, 0 /* timeoutMs */,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004914 TRACK_DEFAULT, TYPE_NONE, cbHandler);
4915 }
4916
4917 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004918 * Registers to receive notifications about changes in the system default network. The callbacks
4919 * will continue to be called until either the application exits or
4920 * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
4921 *
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004922 * This method should not be used to determine networking state seen by applications, because in
4923 * many cases, most or even all application traffic may not use the default network directly,
4924 * and traffic from different applications may go on different networks by default. As an
4925 * example, if a VPN is connected, traffic from all applications might be sent through the VPN
4926 * and not onto the system default network. Applications or system components desiring to do
4927 * determine network state as seen by applications should use other methods such as
4928 * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
4929 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004930 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4931 * number of outstanding requests to 100 per app (identified by their UID), shared with
4932 * all variants of this method, of {@link #requestNetwork} as well as
4933 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4934 * Requesting a network with this method will count toward this limit. If this limit is
4935 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4936 * make sure to unregister the callbacks with
4937 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4938 *
4939 * @param networkCallback The {@link NetworkCallback} that the system will call as the
4940 * system default network changes.
4941 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4942 * @throws RuntimeException if the app already has too many callbacks registered.
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004943 *
4944 * @hide
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004945 */
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004946 @SystemApi(client = MODULE_LIBRARIES)
4947 @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
4948 @RequiresPermission(anyOf = {
4949 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08004950 android.Manifest.permission.NETWORK_SETTINGS,
Quang Luong98858d62023-02-11 00:25:24 +00004951 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08004952 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS})
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004953 public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004954 @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004955 CallbackHandler cbHandler = new CallbackHandler(handler);
4956 sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
Lorenzo Colittia77d05e2021-01-29 20:14:04 +09004957 TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004958 }
4959
4960 /**
junyulaibd123062021-03-15 11:48:48 +08004961 * Registers to receive notifications about the best matching network which satisfy the given
4962 * {@link NetworkRequest}. The callbacks will continue to be called until
4963 * either the application exits or {@link #unregisterNetworkCallback(NetworkCallback)} is
4964 * called.
4965 *
4966 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4967 * number of outstanding requests to 100 per app (identified by their UID), shared with
4968 * {@link #registerNetworkCallback} and its variants and {@link #requestNetwork} as well as
4969 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4970 * Requesting a network with this method will count toward this limit. If this limit is
4971 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4972 * make sure to unregister the callbacks with
4973 * {@link #unregisterNetworkCallback(NetworkCallback)}.
4974 *
4975 *
4976 * @param request {@link NetworkRequest} describing this request.
4977 * @param networkCallback The {@link NetworkCallback} that the system will call as suitable
4978 * networks change state.
4979 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4980 * @throws RuntimeException if the app already has too many callbacks registered.
junyulai5a5c99b2021-03-05 15:51:17 +08004981 */
junyulai5a5c99b2021-03-05 15:51:17 +08004982 @SuppressLint("ExecutorRegistration")
4983 public void registerBestMatchingNetworkCallback(@NonNull NetworkRequest request,
4984 @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4985 final NetworkCapabilities nc = request.networkCapabilities;
4986 final CallbackHandler cbHandler = new CallbackHandler(handler);
junyulai7664f622021-03-12 20:05:08 +08004987 sendRequestForNetwork(nc, networkCallback, 0, LISTEN_FOR_BEST, TYPE_NONE, cbHandler);
junyulai5a5c99b2021-03-05 15:51:17 +08004988 }
4989
4990 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09004991 * Requests bandwidth update for a given {@link Network} and returns whether the update request
4992 * is accepted by ConnectivityService. Once accepted, ConnectivityService will poll underlying
4993 * network connection for updated bandwidth information. The caller will be notified via
4994 * {@link ConnectivityManager.NetworkCallback} if there is an update. Notice that this
4995 * method assumes that the caller has previously called
4996 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} to listen for network
4997 * changes.
4998 *
4999 * @param network {@link Network} specifying which network you're interested.
5000 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5001 */
5002 public boolean requestBandwidthUpdate(@NonNull Network network) {
5003 try {
5004 return mService.requestBandwidthUpdate(network);
5005 } catch (RemoteException e) {
5006 throw e.rethrowFromSystemServer();
5007 }
5008 }
5009
5010 /**
5011 * Unregisters a {@code NetworkCallback} and possibly releases networks originating from
5012 * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and
5013 * {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} calls.
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005014 * If the given {@code NetworkCallback} had previously been used with {@code #requestNetwork},
5015 * any networks that the device brought up only to satisfy that request will be disconnected.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005016 *
5017 * Notifications that would have triggered that {@code NetworkCallback} will immediately stop
5018 * triggering it as soon as this call returns.
5019 *
5020 * @param networkCallback The {@link NetworkCallback} used when making the request.
5021 */
5022 public void unregisterNetworkCallback(@NonNull NetworkCallback networkCallback) {
5023 printStackTrace();
5024 checkCallbackNotNull(networkCallback);
5025 final List<NetworkRequest> reqs = new ArrayList<>();
5026 // Find all requests associated to this callback and stop callback triggers immediately.
5027 // Callback is reusable immediately. http://b/20701525, http://b/35921499.
5028 synchronized (sCallbacks) {
Remi NGUYEN VAN1818dbb2021-03-15 07:31:54 +00005029 if (networkCallback.networkRequest == null) {
5030 throw new IllegalArgumentException("NetworkCallback was not registered");
5031 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005032 if (networkCallback.networkRequest == ALREADY_UNREGISTERED) {
5033 Log.d(TAG, "NetworkCallback was already unregistered");
5034 return;
5035 }
5036 for (Map.Entry<NetworkRequest, NetworkCallback> e : sCallbacks.entrySet()) {
5037 if (e.getValue() == networkCallback) {
5038 reqs.add(e.getKey());
5039 }
5040 }
5041 // TODO: throw exception if callback was registered more than once (http://b/20701525).
5042 for (NetworkRequest r : reqs) {
5043 try {
5044 mService.releaseNetworkRequest(r);
5045 } catch (RemoteException e) {
5046 throw e.rethrowFromSystemServer();
5047 }
5048 // Only remove mapping if rpc was successful.
5049 sCallbacks.remove(r);
5050 }
5051 networkCallback.networkRequest = ALREADY_UNREGISTERED;
5052 }
5053 }
5054
5055 /**
5056 * Unregisters a callback previously registered via
5057 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
5058 *
5059 * @param operation A PendingIntent equal (as defined by {@link Intent#filterEquals}) to the
5060 * PendingIntent passed to
5061 * {@link #registerNetworkCallback(NetworkRequest, android.app.PendingIntent)}.
5062 * Cannot be null.
5063 */
5064 public void unregisterNetworkCallback(@NonNull PendingIntent operation) {
5065 releaseNetworkRequest(operation);
5066 }
5067
5068 /**
5069 * Informs the system whether it should switch to {@code network} regardless of whether it is
5070 * validated or not. If {@code accept} is true, and the network was explicitly selected by the
5071 * user (e.g., by selecting a Wi-Fi network in the Settings app), then the network will become
5072 * the system default network regardless of any other network that's currently connected. If
5073 * {@code always} is true, then the choice is remembered, so that the next time the user
5074 * connects to this network, the system will switch to it.
5075 *
5076 * @param network The network to accept.
5077 * @param accept Whether to accept the network even if unvalidated.
5078 * @param always Whether to remember this choice in the future.
5079 *
5080 * @hide
5081 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005082 @SystemApi(client = MODULE_LIBRARIES)
5083 @RequiresPermission(anyOf = {
5084 android.Manifest.permission.NETWORK_SETTINGS,
5085 android.Manifest.permission.NETWORK_SETUP_WIZARD,
5086 android.Manifest.permission.NETWORK_STACK,
5087 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
5088 public void setAcceptUnvalidated(@NonNull Network network, boolean accept, boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005089 try {
5090 mService.setAcceptUnvalidated(network, accept, always);
5091 } catch (RemoteException e) {
5092 throw e.rethrowFromSystemServer();
5093 }
5094 }
5095
5096 /**
5097 * Informs the system whether it should consider the network as validated even if it only has
5098 * partial connectivity. If {@code accept} is true, then the network will be considered as
5099 * validated even if connectivity is only partial. If {@code always} is true, then the choice
5100 * is remembered, so that the next time the user connects to this network, the system will
5101 * switch to it.
5102 *
5103 * @param network The network to accept.
5104 * @param accept Whether to consider the network as validated even if it has partial
5105 * connectivity.
5106 * @param always Whether to remember this choice in the future.
5107 *
5108 * @hide
5109 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005110 @SystemApi(client = MODULE_LIBRARIES)
5111 @RequiresPermission(anyOf = {
5112 android.Manifest.permission.NETWORK_SETTINGS,
5113 android.Manifest.permission.NETWORK_SETUP_WIZARD,
5114 android.Manifest.permission.NETWORK_STACK,
5115 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
5116 public void setAcceptPartialConnectivity(@NonNull Network network, boolean accept,
5117 boolean always) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005118 try {
5119 mService.setAcceptPartialConnectivity(network, accept, always);
5120 } catch (RemoteException e) {
5121 throw e.rethrowFromSystemServer();
5122 }
5123 }
5124
5125 /**
5126 * Informs the system to penalize {@code network}'s score when it becomes unvalidated. This is
5127 * only meaningful if the system is configured not to penalize such networks, e.g., if the
5128 * {@code config_networkAvoidBadWifi} configuration variable is set to 0 and the {@code
5129 * NETWORK_AVOID_BAD_WIFI setting is unset}.
5130 *
5131 * @param network The network to accept.
5132 *
5133 * @hide
5134 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005135 @SystemApi(client = MODULE_LIBRARIES)
5136 @RequiresPermission(anyOf = {
5137 android.Manifest.permission.NETWORK_SETTINGS,
5138 android.Manifest.permission.NETWORK_SETUP_WIZARD,
5139 android.Manifest.permission.NETWORK_STACK,
5140 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
5141 public void setAvoidUnvalidated(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005142 try {
5143 mService.setAvoidUnvalidated(network);
5144 } catch (RemoteException e) {
5145 throw e.rethrowFromSystemServer();
5146 }
5147 }
5148
5149 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005150 * Temporarily allow bad Wi-Fi to override {@code config_networkAvoidBadWifi} configuration.
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005151 *
5152 * @param timeMs The expired current time. The value should be set within a limited time from
5153 * now.
5154 *
5155 * @hide
5156 */
5157 public void setTestAllowBadWifiUntil(long timeMs) {
5158 try {
5159 mService.setTestAllowBadWifiUntil(timeMs);
5160 } catch (RemoteException e) {
5161 throw e.rethrowFromSystemServer();
5162 }
5163 }
5164
5165 /**
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005166 * Requests that the system open the captive portal app on the specified network.
5167 *
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09005168 * <p>This is to be used on networks where a captive portal was detected, as per
5169 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}.
5170 *
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005171 * @param network The network to log into.
5172 *
5173 * @hide
5174 */
Remi NGUYEN VAN8238a762021-03-16 18:06:06 +09005175 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
5176 @RequiresPermission(anyOf = {
5177 android.Manifest.permission.NETWORK_SETTINGS,
5178 android.Manifest.permission.NETWORK_STACK,
5179 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5180 })
5181 public void startCaptivePortalApp(@NonNull Network network) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005182 try {
5183 mService.startCaptivePortalApp(network);
5184 } catch (RemoteException e) {
5185 throw e.rethrowFromSystemServer();
5186 }
5187 }
5188
5189 /**
5190 * Requests that the system open the captive portal app with the specified extras.
5191 *
5192 * <p>This endpoint is exclusively for use by the NetworkStack and is protected by the
5193 * corresponding permission.
5194 * @param network Network on which the captive portal was detected.
5195 * @param appExtras Extras to include in the app start intent.
5196 * @hide
5197 */
5198 @SystemApi
5199 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5200 public void startCaptivePortalApp(@NonNull Network network, @NonNull Bundle appExtras) {
5201 try {
5202 mService.startCaptivePortalAppInternal(network, appExtras);
5203 } catch (RemoteException e) {
5204 throw e.rethrowFromSystemServer();
5205 }
5206 }
5207
5208 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005209 * Determine whether the device is configured to avoid bad Wi-Fi.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005210 * @hide
5211 */
5212 @SystemApi
5213 @RequiresPermission(anyOf = {
5214 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5215 android.Manifest.permission.NETWORK_STACK})
5216 public boolean shouldAvoidBadWifi() {
5217 try {
5218 return mService.shouldAvoidBadWifi();
5219 } catch (RemoteException e) {
5220 throw e.rethrowFromSystemServer();
5221 }
5222 }
5223
5224 /**
5225 * It is acceptable to briefly use multipath data to provide seamless connectivity for
5226 * time-sensitive user-facing operations when the system default network is temporarily
5227 * unresponsive. The amount of data should be limited (less than one megabyte for every call to
5228 * this method), and the operation should be infrequent to ensure that data usage is limited.
5229 *
5230 * An example of such an operation might be a time-sensitive foreground activity, such as a
5231 * voice command, that the user is performing while walking out of range of a Wi-Fi network.
5232 */
5233 public static final int MULTIPATH_PREFERENCE_HANDOVER = 1 << 0;
5234
5235 /**
5236 * It is acceptable to use small amounts of multipath data on an ongoing basis to provide
5237 * a backup channel for traffic that is primarily going over another network.
5238 *
5239 * An example might be maintaining backup connections to peers or servers for the purpose of
5240 * fast fallback if the default network is temporarily unresponsive or disconnects. The traffic
5241 * on backup paths should be negligible compared to the traffic on the main path.
5242 */
5243 public static final int MULTIPATH_PREFERENCE_RELIABILITY = 1 << 1;
5244
5245 /**
5246 * It is acceptable to use metered data to improve network latency and performance.
5247 */
5248 public static final int MULTIPATH_PREFERENCE_PERFORMANCE = 1 << 2;
5249
5250 /**
5251 * Return value to use for unmetered networks. On such networks we currently set all the flags
5252 * to true.
5253 * @hide
5254 */
5255 public static final int MULTIPATH_PREFERENCE_UNMETERED =
5256 MULTIPATH_PREFERENCE_HANDOVER |
5257 MULTIPATH_PREFERENCE_RELIABILITY |
5258 MULTIPATH_PREFERENCE_PERFORMANCE;
5259
Aaron Huangcff22942021-05-27 16:31:26 +08005260 /** @hide */
5261 @Retention(RetentionPolicy.SOURCE)
5262 @IntDef(flag = true, value = {
5263 MULTIPATH_PREFERENCE_HANDOVER,
5264 MULTIPATH_PREFERENCE_RELIABILITY,
5265 MULTIPATH_PREFERENCE_PERFORMANCE,
5266 })
5267 public @interface MultipathPreference {
5268 }
5269
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005270 /**
5271 * Provides a hint to the calling application on whether it is desirable to use the
5272 * multinetwork APIs (e.g., {@link Network#openConnection}, {@link Network#bindSocket}, etc.)
5273 * for multipath data transfer on this network when it is not the system default network.
5274 * Applications desiring to use multipath network protocols should call this method before
5275 * each such operation.
5276 *
5277 * @param network The network on which the application desires to use multipath data.
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005278 * If {@code null}, this method will return a preference that will generally
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005279 * apply to metered networks.
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005280 * @return a bitwise OR of zero or more of the {@code MULTIPATH_PREFERENCE_*} constants.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005281 */
5282 @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
5283 public @MultipathPreference int getMultipathPreference(@Nullable Network network) {
5284 try {
5285 return mService.getMultipathPreference(network);
5286 } catch (RemoteException e) {
5287 throw e.rethrowFromSystemServer();
5288 }
5289 }
5290
5291 /**
5292 * Resets all connectivity manager settings back to factory defaults.
5293 * @hide
5294 */
Chiachang Wangf9294e72021-03-18 09:44:34 +08005295 @SystemApi(client = MODULE_LIBRARIES)
5296 @RequiresPermission(anyOf = {
5297 android.Manifest.permission.NETWORK_SETTINGS,
5298 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK})
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005299 public void factoryReset() {
5300 try {
5301 mService.factoryReset();
Remi NGUYEN VANe4d1cd92021-06-17 16:27:31 +09005302 getTetheringManager().stopAllTethering();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005303 } catch (RemoteException e) {
5304 throw e.rethrowFromSystemServer();
5305 }
5306 }
5307
5308 /**
5309 * Binds the current process to {@code network}. All Sockets created in the future
5310 * (and not explicitly bound via a bound SocketFactory from
5311 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
5312 * {@code network}. All host name resolutions will be limited to {@code network} as well.
5313 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
5314 * work and all host name resolutions will fail. This is by design so an application doesn't
5315 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
5316 * To clear binding pass {@code null} for {@code network}. Using individually bound
5317 * Sockets created by Network.getSocketFactory().createSocket() and
5318 * performing network-specific host name resolutions via
5319 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
5320 * {@code bindProcessToNetwork}.
5321 *
5322 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
5323 * the current binding.
5324 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5325 */
5326 public boolean bindProcessToNetwork(@Nullable Network network) {
5327 // Forcing callers to call through non-static function ensures ConnectivityManager
5328 // instantiated.
5329 return setProcessDefaultNetwork(network);
5330 }
5331
5332 /**
5333 * Binds the current process to {@code network}. All Sockets created in the future
5334 * (and not explicitly bound via a bound SocketFactory from
5335 * {@link Network#getSocketFactory() Network.getSocketFactory()}) will be bound to
5336 * {@code network}. All host name resolutions will be limited to {@code network} as well.
5337 * Note that if {@code network} ever disconnects, all Sockets created in this way will cease to
5338 * work and all host name resolutions will fail. This is by design so an application doesn't
5339 * accidentally use Sockets it thinks are still bound to a particular {@link Network}.
5340 * To clear binding pass {@code null} for {@code network}. Using individually bound
5341 * Sockets created by Network.getSocketFactory().createSocket() and
5342 * performing network-specific host name resolutions via
5343 * {@link Network#getAllByName Network.getAllByName} is preferred to calling
5344 * {@code setProcessDefaultNetwork}.
5345 *
5346 * @param network The {@link Network} to bind the current process to, or {@code null} to clear
5347 * the current binding.
5348 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5349 * @deprecated This function can throw {@link IllegalStateException}. Use
5350 * {@link #bindProcessToNetwork} instead. {@code bindProcessToNetwork}
5351 * is a direct replacement.
5352 */
5353 @Deprecated
5354 public static boolean setProcessDefaultNetwork(@Nullable Network network) {
5355 int netId = (network == null) ? NETID_UNSET : network.netId;
5356 boolean isSameNetId = (netId == NetworkUtils.getBoundNetworkForProcess());
5357
5358 if (netId != NETID_UNSET) {
5359 netId = network.getNetIdForResolv();
5360 }
5361
5362 if (!NetworkUtils.bindProcessToNetwork(netId)) {
5363 return false;
5364 }
5365
5366 if (!isSameNetId) {
5367 // Set HTTP proxy system properties to match network.
5368 // TODO: Deprecate this static method and replace it with a non-static version.
5369 try {
Remi NGUYEN VAN8a831d62021-02-03 10:18:20 +09005370 Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005371 } catch (SecurityException e) {
5372 // The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
5373 Log.e(TAG, "Can't set proxy properties", e);
5374 }
5375 // Must flush DNS cache as new network may have different DNS resolutions.
Remi NGUYEN VANb2e919f2021-07-02 09:34:36 +09005376 InetAddress.clearDnsCache();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005377 // Must flush socket pool as idle sockets will be bound to previous network and may
5378 // cause subsequent fetches to be performed on old network.
Orion Hodson1f4fa9f2021-05-25 21:02:02 +01005379 NetworkEventDispatcher.getInstance().dispatchNetworkConfigurationChange();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005380 }
5381
5382 return true;
5383 }
5384
5385 /**
5386 * Returns the {@link Network} currently bound to this process via
5387 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
5388 *
5389 * @return {@code Network} to which this process is bound, or {@code null}.
5390 */
5391 @Nullable
5392 public Network getBoundNetworkForProcess() {
Chalard Jean0c7ebe92022-08-03 14:45:47 +09005393 // Forcing callers to call through non-static function ensures ConnectivityManager has been
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005394 // instantiated.
5395 return getProcessDefaultNetwork();
5396 }
5397
5398 /**
5399 * Returns the {@link Network} currently bound to this process via
5400 * {@link #bindProcessToNetwork}, or {@code null} if no {@link Network} is explicitly bound.
5401 *
5402 * @return {@code Network} to which this process is bound, or {@code null}.
5403 * @deprecated Using this function can lead to other functions throwing
5404 * {@link IllegalStateException}. Use {@link #getBoundNetworkForProcess} instead.
5405 * {@code getBoundNetworkForProcess} is a direct replacement.
5406 */
5407 @Deprecated
5408 @Nullable
5409 public static Network getProcessDefaultNetwork() {
5410 int netId = NetworkUtils.getBoundNetworkForProcess();
5411 if (netId == NETID_UNSET) return null;
5412 return new Network(netId);
5413 }
5414
5415 private void unsupportedStartingFrom(int version) {
5416 if (Process.myUid() == Process.SYSTEM_UID) {
5417 // The getApplicationInfo() call we make below is not supported in system context. Let
5418 // the call through here, and rely on the fact that ConnectivityService will refuse to
5419 // allow the system to use these APIs anyway.
5420 return;
5421 }
5422
5423 if (mContext.getApplicationInfo().targetSdkVersion >= version) {
5424 throw new UnsupportedOperationException(
5425 "This method is not supported in target SDK version " + version + " and above");
5426 }
5427 }
5428
5429 // Checks whether the calling app can use the legacy routing API (startUsingNetworkFeature,
5430 // stopUsingNetworkFeature, requestRouteToHost), and if not throw UnsupportedOperationException.
5431 // TODO: convert the existing system users (Tethering, GnssLocationProvider) to the new APIs and
5432 // remove these exemptions. Note that this check is not secure, and apps can still access these
5433 // functions by accessing ConnectivityService directly. However, it should be clear that doing
5434 // so is unsupported and may break in the future. http://b/22728205
5435 private void checkLegacyRoutingApiAccess() {
5436 unsupportedStartingFrom(VERSION_CODES.M);
5437 }
5438
5439 /**
5440 * Binds host resolutions performed by this process to {@code network}.
5441 * {@link #bindProcessToNetwork} takes precedence over this setting.
5442 *
5443 * @param network The {@link Network} to bind host resolutions from the current process to, or
5444 * {@code null} to clear the current binding.
5445 * @return {@code true} on success, {@code false} if the {@link Network} is no longer valid.
5446 * @hide
5447 * @deprecated This is strictly for legacy usage to support {@link #startUsingNetworkFeature}.
5448 */
5449 @Deprecated
5450 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
5451 public static boolean setProcessDefaultNetworkForHostResolution(Network network) {
5452 return NetworkUtils.bindProcessToNetworkForHostResolution(
5453 (network == null) ? NETID_UNSET : network.getNetIdForResolv());
5454 }
5455
5456 /**
5457 * Device is not restricting metered network activity while application is running on
5458 * background.
5459 */
5460 public static final int RESTRICT_BACKGROUND_STATUS_DISABLED = 1;
5461
5462 /**
5463 * Device is restricting metered network activity while application is running on background,
5464 * but application is allowed to bypass it.
5465 * <p>
5466 * In this state, application should take action to mitigate metered network access.
5467 * For example, a music streaming application should switch to a low-bandwidth bitrate.
5468 */
5469 public static final int RESTRICT_BACKGROUND_STATUS_WHITELISTED = 2;
5470
5471 /**
5472 * Device is restricting metered network activity while application is running on background.
5473 * <p>
5474 * In this state, application should not try to use the network while running on background,
5475 * because it would be denied.
5476 */
5477 public static final int RESTRICT_BACKGROUND_STATUS_ENABLED = 3;
5478
5479 /**
5480 * A change in the background metered network activity restriction has occurred.
5481 * <p>
5482 * Applications should call {@link #getRestrictBackgroundStatus()} to check if the restriction
5483 * applies to them.
5484 * <p>
5485 * This is only sent to registered receivers, not manifest receivers.
5486 */
5487 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
5488 public static final String ACTION_RESTRICT_BACKGROUND_CHANGED =
5489 "android.net.conn.RESTRICT_BACKGROUND_CHANGED";
5490
Aaron Huangcff22942021-05-27 16:31:26 +08005491 /** @hide */
5492 @Retention(RetentionPolicy.SOURCE)
5493 @IntDef(flag = false, value = {
5494 RESTRICT_BACKGROUND_STATUS_DISABLED,
5495 RESTRICT_BACKGROUND_STATUS_WHITELISTED,
5496 RESTRICT_BACKGROUND_STATUS_ENABLED,
5497 })
5498 public @interface RestrictBackgroundStatus {
5499 }
5500
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005501 /**
5502 * Determines if the calling application is subject to metered network restrictions while
5503 * running on background.
5504 *
5505 * @return {@link #RESTRICT_BACKGROUND_STATUS_DISABLED},
5506 * {@link #RESTRICT_BACKGROUND_STATUS_ENABLED},
5507 * or {@link #RESTRICT_BACKGROUND_STATUS_WHITELISTED}
5508 */
5509 public @RestrictBackgroundStatus int getRestrictBackgroundStatus() {
5510 try {
Remi NGUYEN VAN1fdeb502021-03-18 14:23:12 +09005511 return mService.getRestrictBackgroundStatusByCaller();
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005512 } catch (RemoteException e) {
5513 throw e.rethrowFromSystemServer();
5514 }
5515 }
5516
5517 /**
5518 * The network watchlist is a list of domains and IP addresses that are associated with
5519 * potentially harmful apps. This method returns the SHA-256 of the watchlist config file
5520 * currently used by the system for validation purposes.
5521 *
5522 * @return Hash of network watchlist config file. Null if config does not exist.
5523 */
5524 @Nullable
5525 public byte[] getNetworkWatchlistConfigHash() {
5526 try {
5527 return mService.getNetworkWatchlistConfigHash();
5528 } catch (RemoteException e) {
5529 Log.e(TAG, "Unable to get watchlist config hash");
5530 throw e.rethrowFromSystemServer();
5531 }
5532 }
5533
5534 /**
5535 * Returns the {@code uid} of the owner of a network connection.
5536 *
5537 * @param protocol The protocol of the connection. Only {@code IPPROTO_TCP} and {@code
5538 * IPPROTO_UDP} currently supported.
5539 * @param local The local {@link InetSocketAddress} of a connection.
5540 * @param remote The remote {@link InetSocketAddress} of a connection.
5541 * @return {@code uid} if the connection is found and the app has permission to observe it
5542 * (e.g., if it is associated with the calling VPN app's VpnService tunnel) or {@link
5543 * android.os.Process#INVALID_UID} if the connection is not found.
Sherri Lin443b7182023-02-08 04:49:29 +01005544 * @throws SecurityException if the caller is not the active VpnService for the current
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005545 * user.
Sherri Lin443b7182023-02-08 04:49:29 +01005546 * @throws IllegalArgumentException if an unsupported protocol is requested.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005547 */
5548 public int getConnectionOwnerUid(
5549 int protocol, @NonNull InetSocketAddress local, @NonNull InetSocketAddress remote) {
5550 ConnectionInfo connectionInfo = new ConnectionInfo(protocol, local, remote);
5551 try {
5552 return mService.getConnectionOwnerUid(connectionInfo);
5553 } catch (RemoteException e) {
5554 throw e.rethrowFromSystemServer();
5555 }
5556 }
5557
5558 private void printStackTrace() {
5559 if (DEBUG) {
5560 final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
5561 final StringBuffer sb = new StringBuffer();
5562 for (int i = 3; i < callStack.length; i++) {
5563 final String stackTrace = callStack[i].toString();
5564 if (stackTrace == null || stackTrace.contains("android.os")) {
5565 break;
5566 }
5567 sb.append(" [").append(stackTrace).append("]");
5568 }
5569 Log.d(TAG, "StackLog:" + sb.toString());
5570 }
5571 }
5572
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005573 /** @hide */
5574 public TestNetworkManager startOrGetTestNetworkManager() {
5575 final IBinder tnBinder;
5576 try {
5577 tnBinder = mService.startOrGetTestNetworkService();
5578 } catch (RemoteException e) {
5579 throw e.rethrowFromSystemServer();
5580 }
5581
5582 return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
5583 }
5584
Remi NGUYEN VAN91444ca2021-01-15 23:02:47 +09005585 /** @hide */
5586 public ConnectivityDiagnosticsManager createDiagnosticsManager() {
5587 return new ConnectivityDiagnosticsManager(mContext, mService);
5588 }
5589
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005590 /**
5591 * Simulates a Data Stall for the specified Network.
5592 *
5593 * <p>This method should only be used for tests.
5594 *
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005595 * <p>The caller must be the owner of the specified Network. This simulates a data stall to
5596 * have the system behave as if it had happened, but does not actually stall connectivity.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005597 *
5598 * @param detectionMethod The detection method used to identify the Data Stall.
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005599 * See ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_*.
5600 * @param timestampMillis The timestamp at which the stall 'occurred', in milliseconds, as per
5601 * SystemClock.elapsedRealtime.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005602 * @param network The Network for which a Data Stall is being simluated.
5603 * @param extras The PersistableBundle of extras included in the Data Stall notification.
5604 * @throws SecurityException if the caller is not the owner of the given network.
5605 * @hide
5606 */
5607 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
5608 @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_TEST_NETWORKS,
5609 android.Manifest.permission.NETWORK_STACK})
Remi NGUYEN VAN564f7f82021-04-08 16:26:20 +09005610 public void simulateDataStall(@DetectionMethod int detectionMethod, long timestampMillis,
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005611 @NonNull Network network, @NonNull PersistableBundle extras) {
5612 try {
5613 mService.simulateDataStall(detectionMethod, timestampMillis, network, extras);
5614 } catch (RemoteException e) {
5615 e.rethrowFromSystemServer();
5616 }
5617 }
5618
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005619 @NonNull
5620 private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
5621
5622 /**
5623 * Registers a {@link QosSocketInfo} with an associated {@link QosCallback}. The callback will
5624 * receive available QoS events related to the {@link Network} and local ip + port
5625 * specified within socketInfo.
5626 * <p/>
5627 * The same {@link QosCallback} must be unregistered before being registered a second time,
5628 * otherwise {@link QosCallbackRegistrationException} is thrown.
5629 * <p/>
5630 * This API does not, in itself, require any permission if called with a network that is not
5631 * restricted. However, the underlying implementation currently only supports the IMS network,
5632 * which is always restricted. That means non-preinstalled callers can't possibly find this API
5633 * useful, because they'd never be called back on networks that they would have access to.
5634 *
5635 * @throws SecurityException if {@link QosSocketInfo#getNetwork()} is restricted and the app is
5636 * missing CONNECTIVITY_USE_RESTRICTED_NETWORKS permission.
5637 * @throws QosCallback.QosCallbackRegistrationException if qosCallback is already registered.
5638 * @throws RuntimeException if the app already has too many callbacks registered.
5639 *
5640 * Exceptions after the time of registration is passed through
5641 * {@link QosCallback#onError(QosCallbackException)}. see: {@link QosCallbackException}.
5642 *
5643 * @param socketInfo the socket information used to match QoS events
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005644 * @param executor The executor on which the callback will be invoked. The provided
5645 * {@link Executor} must run callback sequentially, otherwise the order of
Daniel Bright686d5d22021-03-10 11:51:50 -08005646 * callbacks cannot be guaranteed.onQosCallbackRegistered
5647 * @param callback receives qos events that satisfy socketInfo
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005648 *
5649 * @hide
5650 */
5651 @SystemApi
5652 public void registerQosCallback(@NonNull final QosSocketInfo socketInfo,
Daniel Bright686d5d22021-03-10 11:51:50 -08005653 @CallbackExecutor @NonNull final Executor executor,
5654 @NonNull final QosCallback callback) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005655 Objects.requireNonNull(socketInfo, "socketInfo must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005656 Objects.requireNonNull(executor, "executor must be non-null");
Daniel Bright686d5d22021-03-10 11:51:50 -08005657 Objects.requireNonNull(callback, "callback must be non-null");
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005658
5659 try {
5660 synchronized (mQosCallbackConnections) {
5661 if (getQosCallbackConnection(callback) == null) {
5662 final QosCallbackConnection connection =
5663 new QosCallbackConnection(this, callback, executor);
5664 mQosCallbackConnections.add(connection);
5665 mService.registerQosSocketCallback(socketInfo, connection);
5666 } else {
5667 Log.e(TAG, "registerQosCallback: Callback already registered");
5668 throw new QosCallbackRegistrationException();
5669 }
5670 }
5671 } catch (final RemoteException e) {
5672 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5673
5674 // The same unregister method method is called for consistency even though nothing
5675 // will be sent to the ConnectivityService since the callback was never successfully
5676 // registered.
5677 unregisterQosCallback(callback);
5678 e.rethrowFromSystemServer();
5679 } catch (final ServiceSpecificException e) {
5680 Log.e(TAG, "registerQosCallback: Error while registering ", e);
5681 unregisterQosCallback(callback);
5682 throw convertServiceException(e);
5683 }
5684 }
5685
5686 /**
5687 * Unregisters the given {@link QosCallback}. The {@link QosCallback} will no longer receive
5688 * events once unregistered and can be registered a second time.
5689 * <p/>
5690 * If the {@link QosCallback} does not have an active registration, it is a no-op.
5691 *
5692 * @param callback the callback being unregistered
5693 *
5694 * @hide
5695 */
5696 @SystemApi
5697 public void unregisterQosCallback(@NonNull final QosCallback callback) {
5698 Objects.requireNonNull(callback, "The callback must be non-null");
5699 try {
5700 synchronized (mQosCallbackConnections) {
5701 final QosCallbackConnection connection = getQosCallbackConnection(callback);
5702 if (connection != null) {
5703 connection.stopReceivingMessages();
5704 mService.unregisterQosCallback(connection);
5705 mQosCallbackConnections.remove(connection);
5706 } else {
5707 Log.d(TAG, "unregisterQosCallback: Callback not registered");
5708 }
5709 }
5710 } catch (final RemoteException e) {
5711 Log.e(TAG, "unregisterQosCallback: Error while unregistering ", e);
5712 e.rethrowFromSystemServer();
5713 }
5714 }
5715
5716 /**
5717 * Gets the connection related to the callback.
5718 *
5719 * @param callback the callback to look up
5720 * @return the related connection
5721 */
5722 @Nullable
5723 private QosCallbackConnection getQosCallbackConnection(final QosCallback callback) {
5724 for (final QosCallbackConnection connection : mQosCallbackConnections) {
5725 // Checking by reference here is intentional
5726 if (connection.getCallback() == callback) {
5727 return connection;
5728 }
5729 }
5730 return null;
5731 }
5732
5733 /**
Roshan Piuse08bc182020-12-22 15:10:42 -08005734 * Request a network to satisfy a set of {@link NetworkCapabilities}, but
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005735 * does not cause any networks to retain the NET_CAPABILITY_FOREGROUND capability. This can
5736 * be used to request that the system provide a network without causing the network to be
5737 * in the foreground.
5738 *
5739 * <p>This method will attempt to find the best network that matches the passed
5740 * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
5741 * criteria. The platform will evaluate which network is the best at its own discretion.
5742 * Throughput, latency, cost per byte, policy, user preference and other considerations
5743 * may be factored in the decision of what is considered the best network.
5744 *
5745 * <p>As long as this request is outstanding, the platform will try to maintain the best network
5746 * matching this request, while always attempting to match the request to a better network if
5747 * possible. If a better match is found, the platform will switch this request to the now-best
5748 * network and inform the app of the newly best network by invoking
5749 * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
5750 * will not try to maintain any other network than the best one currently matching the request:
5751 * a network not matching any network request may be disconnected at any time.
5752 *
5753 * <p>For example, an application could use this method to obtain a connected cellular network
5754 * even if the device currently has a data connection over Ethernet. This may cause the cellular
5755 * radio to consume additional power. Or, an application could inform the system that it wants
5756 * a network supporting sending MMSes and have the system let it know about the currently best
5757 * MMS-supporting network through the provided {@link NetworkCallback}.
5758 *
5759 * <p>The status of the request can be followed by listening to the various callbacks described
5760 * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
5761 * used to direct traffic to the network (although accessing some networks may be subject to
5762 * holding specific permissions). Callers will learn about the specific characteristics of the
5763 * network through
5764 * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
5765 * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
5766 * provided {@link NetworkCallback} will only be invoked due to changes in the best network
5767 * matching the request at any given time; therefore when a better network matching the request
5768 * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
5769 * with the new network after which no further updates are given about the previously-best
5770 * network, unless it becomes the best again at some later time. All callbacks are invoked
5771 * in order on the same thread, which by default is a thread created by the framework running
5772 * in the app.
5773 *
5774 * <p>This{@link NetworkRequest} will live until released via
5775 * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
5776 * which point the system may let go of the network at any time.
5777 *
5778 * <p>It is presently unsupported to request a network with mutable
5779 * {@link NetworkCapabilities} such as
5780 * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
5781 * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
5782 * as these {@code NetworkCapabilities} represent states that a particular
5783 * network may never attain, and whether a network will attain these states
5784 * is unknown prior to bringing up the network so the framework does not
5785 * know how to go about satisfying a request with these capabilities.
5786 *
5787 * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
5788 * number of outstanding requests to 100 per app (identified by their UID), shared with
5789 * all variants of this method, of {@link #registerNetworkCallback} as well as
5790 * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
5791 * Requesting a network with this method will count toward this limit. If this limit is
5792 * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
5793 * make sure to unregister the callbacks with
5794 * {@link #unregisterNetworkCallback(NetworkCallback)}.
5795 *
5796 * @param request {@link NetworkRequest} describing this request.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005797 * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
5798 * the callback must not be shared - it uniquely specifies this request.
junyulaica657cb2021-04-15 00:39:49 +08005799 * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
5800 * If null, the callback is invoked on the default internal Handler.
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005801 * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
5802 * @throws SecurityException if missing the appropriate permissions.
5803 * @throws RuntimeException if the app already has too many callbacks registered.
5804 *
5805 * @hide
5806 */
5807 @SystemApi(client = MODULE_LIBRARIES)
5808 @SuppressLint("ExecutorRegistration")
5809 @RequiresPermission(anyOf = {
5810 android.Manifest.permission.NETWORK_SETTINGS,
5811 android.Manifest.permission.NETWORK_STACK,
5812 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5813 })
5814 public void requestBackgroundNetwork(@NonNull NetworkRequest request,
junyulaica657cb2021-04-15 00:39:49 +08005815 @NonNull NetworkCallback networkCallback,
5816 @SuppressLint("ListenerLast") @NonNull Handler handler) {
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005817 final NetworkCapabilities nc = request.networkCapabilities;
5818 sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
junyulaidbb70462021-03-09 20:49:48 +08005819 TYPE_NONE, new CallbackHandler(handler));
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09005820 }
James Mattis12aeab82021-01-10 14:24:24 -08005821
5822 /**
James Mattis12aeab82021-01-10 14:24:24 -08005823 * Used by automotive devices to set the network preferences used to direct traffic at an
5824 * application level as per the given OemNetworkPreferences. An example use-case would be an
5825 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
5826 * vehicle via a particular network.
5827 *
5828 * Calling this will overwrite the existing preference.
5829 *
5830 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
5831 * @param executor the executor on which listener will be invoked.
5832 * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
5833 * communicate completion of setOemNetworkPreference(). This will only be
5834 * called once upon successful completion of setOemNetworkPreference().
5835 * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
5836 * @throws SecurityException if missing the appropriate permissions.
5837 * @throws UnsupportedOperationException if called on a non-automotive device.
James Mattis6e2d7022021-01-26 16:23:52 -08005838 * @hide
James Mattis12aeab82021-01-10 14:24:24 -08005839 */
James Mattis6e2d7022021-01-26 16:23:52 -08005840 @SystemApi
James Mattisa46c1442021-01-26 14:05:36 -08005841 @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
James Mattis6e2d7022021-01-26 16:23:52 -08005842 public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
James Mattis12aeab82021-01-10 14:24:24 -08005843 @Nullable @CallbackExecutor final Executor executor,
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005844 @Nullable final Runnable listener) {
James Mattis12aeab82021-01-10 14:24:24 -08005845 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
5846 if (null != listener) {
5847 Objects.requireNonNull(executor, "Executor must be non-null");
5848 }
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005849 final IOnCompleteListener listenerInternal = listener == null ? null :
5850 new IOnCompleteListener.Stub() {
James Mattis12aeab82021-01-10 14:24:24 -08005851 @Override
5852 public void onComplete() {
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005853 executor.execute(listener::run);
James Mattis12aeab82021-01-10 14:24:24 -08005854 }
5855 };
5856
5857 try {
5858 mService.setOemNetworkPreference(preference, listenerInternal);
5859 } catch (RemoteException e) {
5860 Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
5861 throw e.rethrowFromSystemServer();
5862 }
5863 }
lucaslin5cdbcfb2021-03-12 00:46:33 +08005864
Chalard Jeanad565e22021-02-25 17:23:40 +09005865 /**
5866 * Request that a user profile is put by default on a network matching a given preference.
5867 *
5868 * See the documentation for the individual preferences for a description of the supported
5869 * behaviors.
5870 *
5871 * @param profile the profile concerned.
5872 * @param preference the preference for this profile.
5873 * @param executor an executor to execute the listener on. Optional if listener is null.
5874 * @param listener an optional listener to listen for completion of the operation.
5875 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5876 * @throws SecurityException if missing the appropriate permissions.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005877 * @deprecated Use {@link #setProfileNetworkPreferences(UserHandle, List, Executor, Runnable)}
5878 * instead as it provides a more flexible API with more options.
Chalard Jeanad565e22021-02-25 17:23:40 +09005879 * @hide
5880 */
Chalard Jean0a4aefc2021-03-03 16:37:13 +09005881 // This function is for establishing per-profile default networking and can only be called by
5882 // the device policy manager, running as the system server. It would make no sense to call it
5883 // on a context for a user because it does not establish a setting on behalf of a user, rather
5884 // it establishes a setting for a user on behalf of the DPM.
5885 @SuppressLint({"UserHandle"})
5886 @SystemApi(client = MODULE_LIBRARIES)
Chalard Jeanad565e22021-02-25 17:23:40 +09005887 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005888 @Deprecated
Chalard Jeanad565e22021-02-25 17:23:40 +09005889 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005890 @ProfileNetworkPreferencePolicy final int preference,
5891 @Nullable @CallbackExecutor final Executor executor,
5892 @Nullable final Runnable listener) {
5893
5894 ProfileNetworkPreference.Builder preferenceBuilder =
5895 new ProfileNetworkPreference.Builder();
5896 preferenceBuilder.setPreference(preference);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -08005897 if (preference != PROFILE_NETWORK_PREFERENCE_DEFAULT) {
5898 preferenceBuilder.setPreferenceEnterpriseId(NET_ENTERPRISE_ID_1);
5899 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005900 setProfileNetworkPreferences(profile,
5901 List.of(preferenceBuilder.build()), executor, listener);
5902 }
5903
5904 /**
5905 * Set a list of default network selection policies for a user profile.
5906 *
5907 * Calling this API with a user handle defines the entire policy for that user handle.
5908 * It will overwrite any setting previously set for the same user profile,
5909 * and not affect previously set settings for other handles.
5910 *
5911 * Call this API with an empty list to remove settings for this user profile.
5912 *
5913 * See {@link ProfileNetworkPreference} for more details on each preference
5914 * parameter.
5915 *
5916 * @param profile the user profile for which the preference is being set.
5917 * @param profileNetworkPreferences the list of profile network preferences for the
5918 * provided profile.
5919 * @param executor an executor to execute the listener on. Optional if listener is null.
5920 * @param listener an optional listener to listen for completion of the operation.
5921 * @throws IllegalArgumentException if {@code profile} is not a valid user profile.
5922 * @throws SecurityException if missing the appropriate permissions.
5923 * @hide
5924 */
5925 @SystemApi(client = MODULE_LIBRARIES)
5926 @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
5927 public void setProfileNetworkPreferences(
5928 @NonNull final UserHandle profile,
5929 @NonNull List<ProfileNetworkPreference> profileNetworkPreferences,
Chalard Jeanad565e22021-02-25 17:23:40 +09005930 @Nullable @CallbackExecutor final Executor executor,
5931 @Nullable final Runnable listener) {
5932 if (null != listener) {
5933 Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener");
5934 }
5935 final IOnCompleteListener proxy;
5936 if (null == listener) {
5937 proxy = null;
5938 } else {
5939 proxy = new IOnCompleteListener.Stub() {
5940 @Override
5941 public void onComplete() {
5942 executor.execute(listener::run);
5943 }
5944 };
5945 }
5946 try {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005947 mService.setProfileNetworkPreferences(profile, profileNetworkPreferences, proxy);
Chalard Jeanad565e22021-02-25 17:23:40 +09005948 } catch (RemoteException e) {
5949 throw e.rethrowFromSystemServer();
5950 }
5951 }
5952
lucaslin5cdbcfb2021-03-12 00:46:33 +08005953 // The first network ID of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005954 private static final int TUN_INTF_NETID_START = 0xFC00; // 0xFC00 = 64512
lucaslin5cdbcfb2021-03-12 00:46:33 +08005955 // The network ID range of IPSec tunnel interface.
lucaslinc296fcc2021-03-15 17:24:12 +08005956 private static final int TUN_INTF_NETID_RANGE = 0x0400; // 0x0400 = 1024
lucaslin5cdbcfb2021-03-12 00:46:33 +08005957
5958 /**
5959 * Get the network ID range reserved for IPSec tunnel interfaces.
5960 *
5961 * @return A Range which indicates the network ID range of IPSec tunnel interface.
5962 * @hide
5963 */
5964 @SystemApi(client = MODULE_LIBRARIES)
5965 @NonNull
5966 public static Range<Integer> getIpSecNetIdRange() {
5967 return new Range(TUN_INTF_NETID_START, TUN_INTF_NETID_START + TUN_INTF_NETID_RANGE - 1);
5968 }
markchien738ad912021-12-09 18:15:45 +08005969
5970 /**
Junyu Laidf210362023-10-24 02:47:50 +00005971 * Sets data saver switch.
5972 *
5973 * @param enable True if enable.
5974 * @throws IllegalStateException if failed.
5975 * @hide
5976 */
5977 @FlaggedApi(Flags.SET_DATA_SAVER_VIA_CM)
5978 @SystemApi(client = MODULE_LIBRARIES)
5979 @RequiresPermission(anyOf = {
5980 android.Manifest.permission.NETWORK_SETTINGS,
5981 android.Manifest.permission.NETWORK_STACK,
5982 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
5983 })
5984 public void setDataSaverEnabled(final boolean enable) {
5985 try {
5986 mService.setDataSaverEnabled(enable);
5987 } catch (RemoteException e) {
5988 throw e.rethrowFromSystemServer();
5989 }
5990 }
5991
5992 /**
markchiene46042b2022-03-02 18:07:35 +08005993 * Adds the specified UID to the list of UIds that are allowed to use data on metered networks
5994 * even when background data is restricted. The deny list takes precedence over the allow list.
markchien738ad912021-12-09 18:15:45 +08005995 *
5996 * @param uid uid of target app
markchien68cfadc2022-01-14 13:39:54 +08005997 * @throws IllegalStateException if updating allow list failed.
markchien738ad912021-12-09 18:15:45 +08005998 * @hide
5999 */
6000 @SystemApi(client = MODULE_LIBRARIES)
6001 @RequiresPermission(anyOf = {
6002 android.Manifest.permission.NETWORK_SETTINGS,
6003 android.Manifest.permission.NETWORK_STACK,
6004 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6005 })
markchiene46042b2022-03-02 18:07:35 +08006006 public void addUidToMeteredNetworkAllowList(final int uid) {
markchien738ad912021-12-09 18:15:45 +08006007 try {
markchiene46042b2022-03-02 18:07:35 +08006008 mService.updateMeteredNetworkAllowList(uid, true /* add */);
markchien738ad912021-12-09 18:15:45 +08006009 } catch (RemoteException e) {
6010 throw e.rethrowFromSystemServer();
markchien738ad912021-12-09 18:15:45 +08006011 }
6012 }
6013
6014 /**
markchiene46042b2022-03-02 18:07:35 +08006015 * Removes the specified UID from the list of UIDs that are allowed to use background data on
6016 * metered networks when background data is restricted. The deny list takes precedence over
6017 * the allow list.
6018 *
6019 * @param uid uid of target app
6020 * @throws IllegalStateException if updating allow list failed.
6021 * @hide
6022 */
6023 @SystemApi(client = MODULE_LIBRARIES)
6024 @RequiresPermission(anyOf = {
6025 android.Manifest.permission.NETWORK_SETTINGS,
6026 android.Manifest.permission.NETWORK_STACK,
6027 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6028 })
6029 public void removeUidFromMeteredNetworkAllowList(final int uid) {
6030 try {
6031 mService.updateMeteredNetworkAllowList(uid, false /* remove */);
6032 } catch (RemoteException e) {
6033 throw e.rethrowFromSystemServer();
6034 }
6035 }
6036
6037 /**
6038 * Adds the specified UID to the list of UIDs that are not allowed to use background data on
6039 * metered networks. Takes precedence over {@link #addUidToMeteredNetworkAllowList}.
markchien738ad912021-12-09 18:15:45 +08006040 *
6041 * @param uid uid of target app
markchien68cfadc2022-01-14 13:39:54 +08006042 * @throws IllegalStateException if updating deny list failed.
markchien738ad912021-12-09 18:15:45 +08006043 * @hide
6044 */
6045 @SystemApi(client = MODULE_LIBRARIES)
6046 @RequiresPermission(anyOf = {
6047 android.Manifest.permission.NETWORK_SETTINGS,
6048 android.Manifest.permission.NETWORK_STACK,
6049 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6050 })
markchiene46042b2022-03-02 18:07:35 +08006051 public void addUidToMeteredNetworkDenyList(final int uid) {
markchien738ad912021-12-09 18:15:45 +08006052 try {
markchiene46042b2022-03-02 18:07:35 +08006053 mService.updateMeteredNetworkDenyList(uid, true /* add */);
6054 } catch (RemoteException e) {
6055 throw e.rethrowFromSystemServer();
6056 }
6057 }
6058
6059 /**
Chalard Jean0c7ebe92022-08-03 14:45:47 +09006060 * Removes the specified UID from the list of UIDs that can use background data on metered
markchiene46042b2022-03-02 18:07:35 +08006061 * networks if background data is not restricted. The deny list takes precedence over the
6062 * allow list.
6063 *
6064 * @param uid uid of target app
6065 * @throws IllegalStateException if updating deny list failed.
6066 * @hide
6067 */
6068 @SystemApi(client = MODULE_LIBRARIES)
6069 @RequiresPermission(anyOf = {
6070 android.Manifest.permission.NETWORK_SETTINGS,
6071 android.Manifest.permission.NETWORK_STACK,
6072 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6073 })
6074 public void removeUidFromMeteredNetworkDenyList(final int uid) {
6075 try {
6076 mService.updateMeteredNetworkDenyList(uid, false /* remove */);
markchien738ad912021-12-09 18:15:45 +08006077 } catch (RemoteException e) {
6078 throw e.rethrowFromSystemServer();
markchiene1561fa2021-12-09 22:00:56 +08006079 }
6080 }
6081
6082 /**
6083 * Sets a firewall rule for the specified UID on the specified chain.
6084 *
6085 * @param chain target chain.
6086 * @param uid uid to allow/deny.
markchien3c04e662022-03-22 16:29:56 +08006087 * @param rule firewall rule to allow/drop packets.
markchien68cfadc2022-01-14 13:39:54 +08006088 * @throws IllegalStateException if updating firewall rule failed.
markchien3c04e662022-03-22 16:29:56 +08006089 * @throws IllegalArgumentException if {@code rule} is not a valid rule.
markchiene1561fa2021-12-09 22:00:56 +08006090 * @hide
6091 */
6092 @SystemApi(client = MODULE_LIBRARIES)
6093 @RequiresPermission(anyOf = {
6094 android.Manifest.permission.NETWORK_SETTINGS,
6095 android.Manifest.permission.NETWORK_STACK,
6096 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6097 })
markchien3c04e662022-03-22 16:29:56 +08006098 public void setUidFirewallRule(@FirewallChain final int chain, final int uid,
6099 @FirewallRule final int rule) {
markchiene1561fa2021-12-09 22:00:56 +08006100 try {
markchien3c04e662022-03-22 16:29:56 +08006101 mService.setUidFirewallRule(chain, uid, rule);
markchiene1561fa2021-12-09 22:00:56 +08006102 } catch (RemoteException e) {
6103 throw e.rethrowFromSystemServer();
markchien738ad912021-12-09 18:15:45 +08006104 }
6105 }
markchien98a6f952022-01-13 23:43:53 +08006106
6107 /**
Motomu Utsumi900b8062023-01-19 16:16:49 +09006108 * Get firewall rule of specified firewall chain on specified uid.
6109 *
6110 * @param chain target chain.
6111 * @param uid target uid
6112 * @return either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
6113 * @throws UnsupportedOperationException if called on pre-T devices.
6114 * @throws ServiceSpecificException in case of failure, with an error code indicating the
6115 * cause of the failure.
6116 * @hide
6117 */
6118 @RequiresPermission(anyOf = {
6119 android.Manifest.permission.NETWORK_SETTINGS,
6120 android.Manifest.permission.NETWORK_STACK,
6121 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6122 })
6123 public int getUidFirewallRule(@FirewallChain final int chain, final int uid) {
6124 try {
6125 return mService.getUidFirewallRule(chain, uid);
6126 } catch (RemoteException e) {
6127 throw e.rethrowFromSystemServer();
6128 }
6129 }
6130
6131 /**
markchien98a6f952022-01-13 23:43:53 +08006132 * Enables or disables the specified firewall chain.
6133 *
6134 * @param chain target chain.
6135 * @param enable whether the chain should be enabled.
Motomu Utsumi18b287d2022-06-19 10:45:30 +00006136 * @throws UnsupportedOperationException if called on pre-T devices.
markchien68cfadc2022-01-14 13:39:54 +08006137 * @throws IllegalStateException if enabling or disabling the firewall chain failed.
markchien98a6f952022-01-13 23:43:53 +08006138 * @hide
6139 */
6140 @SystemApi(client = MODULE_LIBRARIES)
6141 @RequiresPermission(anyOf = {
6142 android.Manifest.permission.NETWORK_SETTINGS,
6143 android.Manifest.permission.NETWORK_STACK,
6144 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6145 })
6146 public void setFirewallChainEnabled(@FirewallChain final int chain, final boolean enable) {
6147 try {
6148 mService.setFirewallChainEnabled(chain, enable);
6149 } catch (RemoteException e) {
6150 throw e.rethrowFromSystemServer();
6151 }
6152 }
markchien00a0bed2022-01-13 23:46:13 +08006153
6154 /**
Motomu Utsumi25cf86f2022-06-27 08:50:19 +00006155 * Get the specified firewall chain's status.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +00006156 *
6157 * @param chain target chain.
6158 * @return {@code true} if chain is enabled, {@code false} if chain is disabled.
6159 * @throws UnsupportedOperationException if called on pre-T devices.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +00006160 * @throws ServiceSpecificException in case of failure, with an error code indicating the
6161 * cause of the failure.
6162 * @hide
6163 */
6164 @RequiresPermission(anyOf = {
6165 android.Manifest.permission.NETWORK_SETTINGS,
6166 android.Manifest.permission.NETWORK_STACK,
6167 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6168 })
6169 public boolean getFirewallChainEnabled(@FirewallChain final int chain) {
6170 try {
6171 return mService.getFirewallChainEnabled(chain);
6172 } catch (RemoteException e) {
6173 throw e.rethrowFromSystemServer();
6174 }
6175 }
6176
6177 /**
markchien00a0bed2022-01-13 23:46:13 +08006178 * Replaces the contents of the specified UID-based firewall chain.
6179 *
6180 * @param chain target chain to replace.
6181 * @param uids The list of UIDs to be placed into chain.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +00006182 * @throws UnsupportedOperationException if called on pre-T devices.
markchien00a0bed2022-01-13 23:46:13 +08006183 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
6184 * @hide
6185 */
6186 @SystemApi(client = MODULE_LIBRARIES)
6187 @RequiresPermission(anyOf = {
6188 android.Manifest.permission.NETWORK_SETTINGS,
6189 android.Manifest.permission.NETWORK_STACK,
6190 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
6191 })
6192 public void replaceFirewallChain(@FirewallChain final int chain, @NonNull final int[] uids) {
6193 Objects.requireNonNull(uids);
6194 try {
6195 mService.replaceFirewallChain(chain, uids);
6196 } catch (RemoteException e) {
6197 throw e.rethrowFromSystemServer();
6198 }
6199 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -08006200
Junyu Laie0031522023-08-29 18:32:57 +08006201 /**
6202 * Return whether the network is blocked for the given uid.
6203 *
6204 * Similar to {@link NetworkPolicyManager#isUidNetworkingBlocked}, but directly reads the BPF
6205 * maps and therefore considerably faster. For use by the NetworkStack process only.
6206 *
6207 * @param uid The target uid.
6208 * @return True if all networking is blocked. Otherwise, false.
6209 * @throws IllegalStateException if the map cannot be opened.
6210 * @throws ServiceSpecificException if the read fails.
6211 * @hide
6212 */
6213 // This isn't protected by a standard Android permission since it can't
6214 // afford to do IPC for performance reasons. Instead, the access control
6215 // is provided by linux file group permission AID_NET_BW_ACCT and the
6216 // selinux context fs_bpf_net*.
6217 // Only the system server process and the network stack have access.
6218 // TODO: Expose api when ready.
6219 // @SystemApi(client = MODULE_LIBRARIES)
6220 @RequiresApi(Build.VERSION_CODES.TIRAMISU) // BPF maps were only mainlined in T
6221 @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
6222 public boolean isUidNetworkingBlocked(int uid) {
6223 final BpfNetMapsReader reader = BpfNetMapsReader.getInstance();
6224
6225 return reader.isUidBlockedByFirewallChains(uid);
6226
6227 // TODO: If isNetworkMetered is true, check the data saver switch, penalty box
6228 // and happy box rules.
6229 }
6230
Igor Chernyshev9dac6602022-12-13 19:28:32 -08006231 /** @hide */
6232 public IBinder getCompanionDeviceManagerProxyService() {
6233 try {
6234 return mService.getCompanionDeviceManagerProxyService();
6235 } catch (RemoteException e) {
6236 throw e.rethrowFromSystemServer();
6237 }
6238 }
Chalard Jean2fb66f12023-08-25 12:50:37 +09006239
6240 private static final Object sRoutingCoordinatorManagerLock = new Object();
6241 @GuardedBy("sRoutingCoordinatorManagerLock")
6242 private static RoutingCoordinatorManager sRoutingCoordinatorManager = null;
6243 /** @hide */
6244 @RequiresApi(Build.VERSION_CODES.S)
6245 public RoutingCoordinatorManager getRoutingCoordinatorManager() {
6246 try {
6247 synchronized (sRoutingCoordinatorManagerLock) {
6248 if (null == sRoutingCoordinatorManager) {
6249 sRoutingCoordinatorManager = new RoutingCoordinatorManager(mContext,
6250 IRoutingCoordinator.Stub.asInterface(
6251 mService.getRoutingCoordinatorService()));
6252 }
6253 return sRoutingCoordinatorManager;
6254 }
6255 } catch (RemoteException e) {
6256 throw e.rethrowFromSystemServer();
6257 }
6258 }
Remi NGUYEN VANfbbccbc2021-01-15 18:08:24 +09006259}