blob: 77b7f16671a0befa7125f1494fb41a914076cd58 [file] [log] [blame]
Ken Shirriffae521152009-12-07 15:56:05 -08001/*
2 * Copyright (C) 2007 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 */
16
17package android.net;
18
Junyu Lai8e58c822022-01-17 17:05:30 +000019import static android.annotation.SystemApi.Client.MODULE_LIBRARIES;
20
Aaron Huang443651d2019-09-27 22:31:22 +080021import android.annotation.NonNull;
Jeff Sharkey1fb74312017-11-29 11:18:23 -070022import android.annotation.SuppressLint;
Christopher Tate5a1878d2014-08-06 14:19:56 -070023import android.annotation.SystemApi;
Benedict Wong083faee2017-12-03 19:42:36 -080024import android.annotation.TestApi;
Jeff Sharkey92790062011-06-24 17:05:24 -070025import android.app.DownloadManager;
26import android.app.backup.BackupManager;
Jeff Sharkey27c8a072016-03-09 16:40:15 -070027import android.app.usage.NetworkStatsManager;
Artur Satayev164c7562019-12-10 17:47:52 +000028import android.compat.annotation.UnsupportedAppUsage;
Jeff Sharkey33936ac2011-05-17 14:55:15 -070029import android.content.Context;
Jeff Sharkey92790062011-06-24 17:05:24 -070030import android.media.MediaPlayer;
Junyu Lai92d5b4c2022-01-19 08:33:21 +000031import android.os.Binder;
Chalard Jean3cfb4992019-04-09 15:46:21 +090032import android.os.Build;
Jeff Sharkey33936ac2011-05-17 14:55:15 -070033import android.os.RemoteException;
Jeff Sharkey33936ac2011-05-17 14:55:15 -070034
Jesse Wilsonb05f41c2011-06-28 19:06:31 -070035import com.android.server.NetworkManagementSocketTagger;
Ken Shirriffae521152009-12-07 15:56:05 -080036
Jesse Wilsonb05f41c2011-06-28 19:06:31 -070037import dalvik.system.SocketTagger;
Jeff Sharkey7407e092011-07-19 23:47:12 -070038
Jeff Sharkey1fb74312017-11-29 11:18:23 -070039import java.io.FileDescriptor;
40import java.io.IOException;
Jeff Sharkey7b124cb2015-12-04 15:21:52 -070041import java.net.DatagramSocket;
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -070042import java.net.Socket;
43import java.net.SocketException;
Ken Shirriffae521152009-12-07 15:56:05 -080044
45/**
Jeff Sharkey27c8a072016-03-09 16:40:15 -070046 * Class that provides network traffic statistics. These statistics include
Dan Egnoreaeb7022010-04-07 17:30:50 -070047 * bytes transmitted and received and network packets transmitted and received,
48 * over all interfaces, over the mobile interface, and on a per-UID basis.
Ken Shirriffae521152009-12-07 15:56:05 -080049 * <p>
Jeff Sharkey27c8a072016-03-09 16:40:15 -070050 * These statistics may not be available on all platforms. If the statistics are
51 * not supported by this device, {@link #UNSUPPORTED} will be returned.
52 * <p>
53 * Note that the statistics returned by this class reset and start from zero
54 * after every reboot. To access more robust historical network statistics data,
55 * use {@link NetworkStatsManager} instead.
Ken Shirriffae521152009-12-07 15:56:05 -080056 */
57public class TrafficStats {
Junyu Lai3f7bb332021-12-28 16:18:43 +000058 private static final String TAG = TrafficStats.class.getSimpleName();
Ken Shirriffae521152009-12-07 15:56:05 -080059 /**
60 * The return value to indicate that the device does not support the statistic.
61 */
62 public final static int UNSUPPORTED = -1;
63
Junyu Lai1d3ce852021-12-27 13:56:59 +000064 /** @hide @deprecated use {@code DataUnit} instead to clarify SI-vs-IEC */
Jeff Sharkeya6886af2018-01-07 16:47:31 -070065 @Deprecated
Jeff Sharkey94a315c2012-02-03 14:50:07 -080066 public static final long KB_IN_BYTES = 1024;
Junyu Lai1d3ce852021-12-27 13:56:59 +000067 /** @hide @deprecated use {@code DataUnit} instead to clarify SI-vs-IEC */
Jeff Sharkeya6886af2018-01-07 16:47:31 -070068 @Deprecated
Jeff Sharkey94a315c2012-02-03 14:50:07 -080069 public static final long MB_IN_BYTES = KB_IN_BYTES * 1024;
Junyu Lai1d3ce852021-12-27 13:56:59 +000070 /** @hide @deprecated use {@code DataUnit} instead to clarify SI-vs-IEC */
Jeff Sharkeya6886af2018-01-07 16:47:31 -070071 @Deprecated
Jeff Sharkey94a315c2012-02-03 14:50:07 -080072 public static final long GB_IN_BYTES = MB_IN_BYTES * 1024;
Junyu Lai1d3ce852021-12-27 13:56:59 +000073 /** @hide @deprecated use {@code DataUnit} instead to clarify SI-vs-IEC */
Jeff Sharkeya6886af2018-01-07 16:47:31 -070074 @Deprecated
Jeff Sharkey6f2ba5e2015-03-18 11:27:19 -070075 public static final long TB_IN_BYTES = GB_IN_BYTES * 1024;
Junyu Lai1d3ce852021-12-27 13:56:59 +000076 /** @hide @deprecated use {@code DataUnit} instead to clarify SI-vs-IEC */
Jeff Sharkeya6886af2018-01-07 16:47:31 -070077 @Deprecated
Jeff Sharkey88069072015-06-15 21:09:10 -070078 public static final long PB_IN_BYTES = TB_IN_BYTES * 1024;
Jeff Sharkey94a315c2012-02-03 14:50:07 -080079
Jeff Sharkey1a3eb882011-05-28 20:56:34 -070080 /**
Jeff Sharkeyc04cda62011-06-19 01:08:12 -070081 * Special UID value used when collecting {@link NetworkStatsHistory} for
82 * removed applications.
83 *
84 * @hide
85 */
86 public static final int UID_REMOVED = -4;
87
88 /**
Jeff Sharkey987f5ff2011-09-16 01:52:49 -070089 * Special UID value used when collecting {@link NetworkStatsHistory} for
90 * tethering traffic.
91 *
92 * @hide
93 */
junyulai55041a42019-11-15 17:15:01 +080094 public static final int UID_TETHERING = NetworkStats.UID_TETHERING;
Jeff Sharkey987f5ff2011-09-16 01:52:49 -070095
96 /**
Chalard Jean8a93ab82019-04-09 11:16:56 +090097 * Tag values in this range are reserved for the network stack. The network stack is
98 * running as UID {@link android.os.Process.NETWORK_STACK_UID} when in the mainline
99 * module separate process, and as the system UID otherwise.
100 */
101 /** @hide */
102 @SystemApi
103 public static final int TAG_NETWORK_STACK_RANGE_START = 0xFFFFFD00;
104 /** @hide */
105 @SystemApi
106 public static final int TAG_NETWORK_STACK_RANGE_END = 0xFFFFFEFF;
107
108 /**
109 * Tags between 0xFFFFFF00 and 0xFFFFFFFF are reserved and used internally by system services
110 * like DownloadManager when performing traffic on behalf of an application.
111 */
112 // Please note there is no enforcement of these constants, so do not rely on them to
113 // determine that the caller is a system caller.
114 /** @hide */
115 @SystemApi
116 public static final int TAG_SYSTEM_IMPERSONATION_RANGE_START = 0xFFFFFF00;
117 /** @hide */
118 @SystemApi
119 public static final int TAG_SYSTEM_IMPERSONATION_RANGE_END = 0xFFFFFF0F;
120
121 /**
122 * Tag values between these ranges are reserved for the network stack to do traffic
123 * on behalf of applications. It is a subrange of the range above.
124 */
125 /** @hide */
126 @SystemApi
127 public static final int TAG_NETWORK_STACK_IMPERSONATION_RANGE_START = 0xFFFFFF80;
128 /** @hide */
129 @SystemApi
130 public static final int TAG_NETWORK_STACK_IMPERSONATION_RANGE_END = 0xFFFFFF8F;
131
132 /**
Jeff Sharkey92790062011-06-24 17:05:24 -0700133 * Default tag value for {@link DownloadManager} traffic.
134 *
135 * @hide
136 */
Jeff Sharkey987f5ff2011-09-16 01:52:49 -0700137 public static final int TAG_SYSTEM_DOWNLOAD = 0xFFFFFF01;
Jeff Sharkey92790062011-06-24 17:05:24 -0700138
139 /**
140 * Default tag value for {@link MediaPlayer} traffic.
141 *
142 * @hide
143 */
Jeff Sharkey987f5ff2011-09-16 01:52:49 -0700144 public static final int TAG_SYSTEM_MEDIA = 0xFFFFFF02;
Jeff Sharkey92790062011-06-24 17:05:24 -0700145
146 /**
Christopher Tatec1c71fd2015-11-10 10:49:20 -0800147 * Default tag value for {@link BackupManager} backup traffic; that is,
148 * traffic from the device to the storage backend.
Jeff Sharkey92790062011-06-24 17:05:24 -0700149 *
150 * @hide
151 */
Jeff Sharkey987f5ff2011-09-16 01:52:49 -0700152 public static final int TAG_SYSTEM_BACKUP = 0xFFFFFF03;
Jeff Sharkey92790062011-06-24 17:05:24 -0700153
Christopher Tatec1c71fd2015-11-10 10:49:20 -0800154 /**
155 * Default tag value for {@link BackupManager} restore traffic; that is,
156 * app data retrieved from the storage backend at install time.
157 *
158 * @hide
159 */
160 public static final int TAG_SYSTEM_RESTORE = 0xFFFFFF04;
161
Jeff Sharkey66dca172016-11-21 12:14:50 -0700162 /**
Jeff Sharkeyb1f97ac2017-08-11 15:04:12 -0600163 * Default tag value for code (typically APKs) downloaded by an app store on
164 * behalf of the app, such as updates.
Jeff Sharkey66dca172016-11-21 12:14:50 -0700165 *
166 * @hide
167 */
Jeff Sharkeyb1f97ac2017-08-11 15:04:12 -0600168 public static final int TAG_SYSTEM_APP = 0xFFFFFF05;
Jeff Sharkey8af5ad12017-06-26 19:50:41 -0600169
Chalard Jean8a93ab82019-04-09 11:16:56 +0900170 // TODO : remove this constant when Wifi code is updated
Jeff Sharkey8af5ad12017-06-26 19:50:41 -0600171 /** @hide */
Jeff Sharkey8af5ad12017-06-26 19:50:41 -0600172 public static final int TAG_SYSTEM_PROBE = 0xFFFFFF42;
Jeff Sharkey66dca172016-11-21 12:14:50 -0700173
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700174 private static INetworkStatsService sStatsService;
175
Chalard Jean3cfb4992019-04-09 15:46:21 +0900176 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700177 private synchronized static INetworkStatsService getStatsService() {
178 if (sStatsService == null) {
Junyu Lai92d5b4c2022-01-19 08:33:21 +0000179 throw new IllegalStateException("TrafficStats not initialized, uid="
180 + Binder.getCallingUid());
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700181 }
182 return sStatsService;
183 }
184
Jeff Sharkey92790062011-06-24 17:05:24 -0700185 /**
Jeff Sharkey33936ac2011-05-17 14:55:15 -0700186 * Snapshot of {@link NetworkStats} when the currently active profiling
187 * session started, or {@code null} if no session active.
188 *
189 * @see #startDataProfiling(Context)
190 * @see #stopDataProfiling(Context)
191 */
192 private static NetworkStats sActiveProfilingStart;
193
194 private static Object sProfilingLock = new Object();
195
Benedict Wong083faee2017-12-03 19:42:36 -0800196 private static final String LOOPBACK_IFACE = "lo";
197
Jeff Sharkey33936ac2011-05-17 14:55:15 -0700198 /**
Junyu Lai92d5b4c2022-01-19 08:33:21 +0000199 * Initialization {@link TrafficStats} with the context, to
200 * allow {@link TrafficStats} to fetch the needed binder.
201 *
202 * @param context a long-lived context, such as the application context or system
203 * server context.
204 * @hide
205 */
206 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
207 @SuppressLint("VisiblySynchronized")
208 public static synchronized void init(@NonNull final Context context) {
209 if (sStatsService != null) {
210 throw new IllegalStateException("TrafficStats is already initialized, uid="
211 + Binder.getCallingUid());
212 }
213 final NetworkStatsManager statsManager =
214 context.getSystemService(NetworkStatsManager.class);
215 sStatsService = statsManager.getBinder();
216 }
217
218 /**
Junyu Lai8e58c822022-01-17 17:05:30 +0000219 * Attach the socket tagger implementation to the current process, to
220 * get notified when a socket's {@link FileDescriptor} is assigned to
221 * a thread. See {@link SocketTagger#set(SocketTagger)}.
222 *
223 * @hide
224 */
225 @SystemApi(client = MODULE_LIBRARIES)
226 public static void attachSocketTagger() {
227 NetworkManagementSocketTagger.install();
228 }
229
230 /**
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700231 * Set active tag to use when accounting {@link Socket} traffic originating
232 * from the current thread. Only one active tag per thread is supported.
233 * <p>
234 * Changes only take effect during subsequent calls to
235 * {@link #tagSocket(Socket)}.
Jeff Sharkey987f5ff2011-09-16 01:52:49 -0700236 * <p>
237 * Tags between {@code 0xFFFFFF00} and {@code 0xFFFFFFFF} are reserved and
238 * used internally by system services like {@link DownloadManager} when
239 * performing traffic on behalf of an application.
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700240 *
241 * @see #clearThreadStatsTag()
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700242 */
Jeff Sharkey92790062011-06-24 17:05:24 -0700243 public static void setThreadStatsTag(int tag) {
Jesse Wilsonb05f41c2011-06-28 19:06:31 -0700244 NetworkManagementSocketTagger.setThreadSocketStatsTag(tag);
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700245 }
246
Jeff Sharkey92790062011-06-24 17:05:24 -0700247 /**
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600248 * Set active tag to use when accounting {@link Socket} traffic originating
Jeff Sharkey289eac12017-01-19 11:55:54 -0700249 * from the current thread. Only one active tag per thread is supported.
250 * <p>
251 * Changes only take effect during subsequent calls to
252 * {@link #tagSocket(Socket)}.
253 * <p>
254 * Tags between {@code 0xFFFFFF00} and {@code 0xFFFFFFFF} are reserved and
255 * used internally by system services like {@link DownloadManager} when
256 * performing traffic on behalf of an application.
257 *
258 * @return the current tag for the calling thread, which can be used to
259 * restore any existing values after a nested operation is finished
260 */
261 public static int getAndSetThreadStatsTag(int tag) {
262 return NetworkManagementSocketTagger.setThreadSocketStatsTag(tag);
263 }
264
265 /**
266 * Set active tag to use when accounting {@link Socket} traffic originating
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600267 * from the current thread. The tag used internally is well-defined to
268 * distinguish all backup-related traffic.
269 *
Christopher Tate5a1878d2014-08-06 14:19:56 -0700270 * @hide
271 */
272 @SystemApi
273 public static void setThreadStatsTagBackup() {
274 setThreadStatsTag(TAG_SYSTEM_BACKUP);
275 }
276
277 /**
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600278 * Set active tag to use when accounting {@link Socket} traffic originating
279 * from the current thread. The tag used internally is well-defined to
280 * distinguish all restore-related traffic.
281 *
Christopher Tatec1c71fd2015-11-10 10:49:20 -0800282 * @hide
283 */
284 @SystemApi
285 public static void setThreadStatsTagRestore() {
286 setThreadStatsTag(TAG_SYSTEM_RESTORE);
287 }
288
289 /**
Jeff Sharkey8af5ad12017-06-26 19:50:41 -0600290 * Set active tag to use when accounting {@link Socket} traffic originating
291 * from the current thread. The tag used internally is well-defined to
Jeff Sharkeyb1f97ac2017-08-11 15:04:12 -0600292 * distinguish all code (typically APKs) downloaded by an app store on
293 * behalf of the app, such as updates.
Jeff Sharkey8af5ad12017-06-26 19:50:41 -0600294 *
295 * @hide
296 */
297 @SystemApi
Jeff Sharkeyb1f97ac2017-08-11 15:04:12 -0600298 public static void setThreadStatsTagApp() {
299 setThreadStatsTag(TAG_SYSTEM_APP);
Jeff Sharkey8af5ad12017-06-26 19:50:41 -0600300 }
301
302 /**
Junyu Laiab2c35e2022-01-18 02:46:23 +0000303 * Set active tag to use when accounting {@link Socket} traffic originating
304 * from the current thread. The tag used internally is well-defined to
305 * distinguish all download provider traffic.
306 *
307 * @hide
308 */
309 @SystemApi
310 public static void setThreadStatsTagDownload() {
311 setThreadStatsTag(TAG_SYSTEM_DOWNLOAD);
312 }
313
314 /**
Alon Albert2c295f02011-07-19 11:16:09 +0300315 * Get the active tag used when accounting {@link Socket} traffic originating
316 * from the current thread. Only one active tag per thread is supported.
317 * {@link #tagSocket(Socket)}.
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700318 *
319 * @see #setThreadStatsTag(int)
Alon Albert2c295f02011-07-19 11:16:09 +0300320 */
321 public static int getThreadStatsTag() {
322 return NetworkManagementSocketTagger.getThreadSocketStatsTag();
323 }
324
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700325 /**
326 * Clear any active tag set to account {@link Socket} traffic originating
327 * from the current thread.
328 *
329 * @see #setThreadStatsTag(int)
330 */
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700331 public static void clearThreadStatsTag() {
Jesse Wilsonb05f41c2011-06-28 19:06:31 -0700332 NetworkManagementSocketTagger.setThreadSocketStatsTag(-1);
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700333 }
334
335 /**
336 * Set specific UID to use when accounting {@link Socket} traffic
337 * originating from the current thread. Designed for use when performing an
Jeff Sharkey17a38752018-03-26 13:11:33 -0600338 * operation on behalf of another application, or when another application
339 * is performing operations on your behalf.
340 * <p>
341 * Any app can <em>accept</em> blame for traffic performed on a socket
342 * originally created by another app by calling this method with the
343 * {@link android.system.Os#getuid()} value. However, only apps holding the
344 * {@code android.Manifest.permission#UPDATE_DEVICE_STATS} permission may
345 * <em>assign</em> blame to another UIDs.
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700346 * <p>
347 * Changes only take effect during subsequent calls to
348 * {@link #tagSocket(Socket)}.
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700349 */
Aurimas Liutikas9de1e0e2020-11-12 18:29:11 -0800350 @SuppressLint("RequiresPermission")
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700351 public static void setThreadStatsUid(int uid) {
Jesse Wilsonb05f41c2011-06-28 19:06:31 -0700352 NetworkManagementSocketTagger.setThreadSocketStatsUid(uid);
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700353 }
354
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600355 /**
Jeff Sharkey17a38752018-03-26 13:11:33 -0600356 * Get the active UID used when accounting {@link Socket} traffic originating
357 * from the current thread. Only one active tag per thread is supported.
358 * {@link #tagSocket(Socket)}.
359 *
360 * @see #setThreadStatsUid(int)
361 */
362 public static int getThreadStatsUid() {
363 return NetworkManagementSocketTagger.getThreadSocketStatsUid();
364 }
365
366 /**
Jeff Sharkey1fb74312017-11-29 11:18:23 -0700367 * Set specific UID to use when accounting {@link Socket} traffic
368 * originating from the current thread as the calling UID. Designed for use
369 * when another application is performing operations on your behalf.
370 * <p>
371 * Changes only take effect during subsequent calls to
372 * {@link #tagSocket(Socket)}.
Jeff Sharkey17a38752018-03-26 13:11:33 -0600373 *
374 * @removed
375 * @deprecated use {@link #setThreadStatsUid(int)} instead.
Jeff Sharkey1fb74312017-11-29 11:18:23 -0700376 */
Jeff Sharkey17a38752018-03-26 13:11:33 -0600377 @Deprecated
Jeff Sharkey1fb74312017-11-29 11:18:23 -0700378 public static void setThreadStatsUidSelf() {
379 setThreadStatsUid(android.os.Process.myUid());
380 }
381
382 /**
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600383 * Clear any active UID set to account {@link Socket} traffic originating
384 * from the current thread.
385 *
386 * @see #setThreadStatsUid(int)
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600387 */
Aurimas Liutikas9de1e0e2020-11-12 18:29:11 -0800388 @SuppressLint("RequiresPermission")
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700389 public static void clearThreadStatsUid() {
Jesse Wilsonb05f41c2011-06-28 19:06:31 -0700390 NetworkManagementSocketTagger.setThreadSocketStatsUid(-1);
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700391 }
392
393 /**
394 * Tag the given {@link Socket} with any statistics parameters active for
395 * the current thread. Subsequent calls always replace any existing
396 * parameters. When finished, call {@link #untagSocket(Socket)} to remove
397 * statistics parameters.
398 *
Jeff Sharkey92790062011-06-24 17:05:24 -0700399 * @see #setThreadStatsTag(int)
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700400 */
401 public static void tagSocket(Socket socket) throws SocketException {
Jesse Wilsonb05f41c2011-06-28 19:06:31 -0700402 SocketTagger.get().tag(socket);
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700403 }
404
405 /**
406 * Remove any statistics parameters from the given {@link Socket}.
koprivac134e242018-07-23 18:19:39 -0700407 * <p>
408 * In Android 8.1 (API level 27) and lower, a socket is automatically
409 * untagged when it's sent to another process using binder IPC with a
410 * {@code ParcelFileDescriptor} container. In Android 9.0 (API level 28)
411 * and higher, the socket tag is kept when the socket is sent to another
412 * process using binder IPC. You can mimic the previous behavior by
413 * calling {@code untagSocket()} before sending the socket to another
414 * process.
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700415 */
416 public static void untagSocket(Socket socket) throws SocketException {
Jesse Wilsonb05f41c2011-06-28 19:06:31 -0700417 SocketTagger.get().untag(socket);
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700418 }
419
420 /**
Jeff Sharkey7b124cb2015-12-04 15:21:52 -0700421 * Tag the given {@link DatagramSocket} with any statistics parameters
422 * active for the current thread. Subsequent calls always replace any
423 * existing parameters. When finished, call
424 * {@link #untagDatagramSocket(DatagramSocket)} to remove statistics
425 * parameters.
426 *
427 * @see #setThreadStatsTag(int)
Jeff Sharkey7b124cb2015-12-04 15:21:52 -0700428 */
429 public static void tagDatagramSocket(DatagramSocket socket) throws SocketException {
430 SocketTagger.get().tag(socket);
431 }
432
433 /**
434 * Remove any statistics parameters from the given {@link DatagramSocket}.
435 */
436 public static void untagDatagramSocket(DatagramSocket socket) throws SocketException {
437 SocketTagger.get().untag(socket);
438 }
439
440 /**
Jeff Sharkey1fb74312017-11-29 11:18:23 -0700441 * Tag the given {@link FileDescriptor} socket with any statistics
442 * parameters active for the current thread. Subsequent calls always replace
443 * any existing parameters. When finished, call
444 * {@link #untagFileDescriptor(FileDescriptor)} to remove statistics
445 * parameters.
446 *
447 * @see #setThreadStatsTag(int)
448 */
449 public static void tagFileDescriptor(FileDescriptor fd) throws IOException {
450 SocketTagger.get().tag(fd);
451 }
452
453 /**
454 * Remove any statistics parameters from the given {@link FileDescriptor}
455 * socket.
456 */
457 public static void untagFileDescriptor(FileDescriptor fd) throws IOException {
458 SocketTagger.get().untag(fd);
459 }
460
461 /**
Jeff Sharkey33936ac2011-05-17 14:55:15 -0700462 * Start profiling data usage for current UID. Only one profiling session
463 * can be active at a time.
464 *
465 * @hide
466 */
467 public static void startDataProfiling(Context context) {
468 synchronized (sProfilingLock) {
469 if (sActiveProfilingStart != null) {
470 throw new IllegalStateException("already profiling data");
471 }
472
473 // take snapshot in time; we calculate delta later
Jeff Sharkey7407e092011-07-19 23:47:12 -0700474 sActiveProfilingStart = getDataLayerSnapshotForUid(context);
Jeff Sharkey33936ac2011-05-17 14:55:15 -0700475 }
476 }
477
478 /**
479 * Stop profiling data usage for current UID.
480 *
481 * @return Detailed {@link NetworkStats} of data that occurred since last
482 * {@link #startDataProfiling(Context)} call.
483 * @hide
484 */
485 public static NetworkStats stopDataProfiling(Context context) {
486 synchronized (sProfilingLock) {
487 if (sActiveProfilingStart == null) {
488 throw new IllegalStateException("not profiling data");
489 }
490
Jeff Sharkeyef7bded2012-01-10 17:24:44 -0800491 // subtract starting values and return delta
492 final NetworkStats profilingStop = getDataLayerSnapshotForUid(context);
493 final NetworkStats profilingDelta = NetworkStats.subtract(
Jeff Sharkeybfe82682012-01-11 18:38:16 -0800494 profilingStop, sActiveProfilingStart, null, null);
Jeff Sharkeyef7bded2012-01-10 17:24:44 -0800495 sActiveProfilingStart = null;
496 return profilingDelta;
Jeff Sharkey33936ac2011-05-17 14:55:15 -0700497 }
498 }
499
500 /**
Jeff Sharkey60ca0232011-08-24 15:42:09 -0700501 * Increment count of network operations performed under the accounting tag
502 * currently active on the calling thread. This can be used to derive
503 * bytes-per-operation.
504 *
505 * @param operationCount Number of operations to increment count by.
506 */
507 public static void incrementOperationCount(int operationCount) {
508 final int tag = getThreadStatsTag();
509 incrementOperationCount(tag, operationCount);
510 }
511
512 /**
Jeff Sharkey7407e092011-07-19 23:47:12 -0700513 * Increment count of network operations performed under the given
514 * accounting tag. This can be used to derive bytes-per-operation.
515 *
516 * @param tag Accounting tag used in {@link #setThreadStatsTag(int)}.
517 * @param operationCount Number of operations to increment count by.
518 */
519 public static void incrementOperationCount(int tag, int operationCount) {
Jeff Sharkey7407e092011-07-19 23:47:12 -0700520 final int uid = android.os.Process.myUid();
521 try {
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700522 getStatsService().incrementOperationCount(uid, tag, operationCount);
Jeff Sharkey7407e092011-07-19 23:47:12 -0700523 } catch (RemoteException e) {
Jeff Sharkeybc08d072016-02-26 13:03:01 -0700524 throw e.rethrowFromSystemServer();
Jeff Sharkey7407e092011-07-19 23:47:12 -0700525 }
526 }
527
Jeff Sharkey920d9042012-04-06 11:12:08 -0700528 /** {@hide} */
529 public static void closeQuietly(INetworkStatsSession session) {
530 // TODO: move to NetworkStatsService once it exists
531 if (session != null) {
532 try {
533 session.close();
534 } catch (RuntimeException rethrown) {
535 throw rethrown;
536 } catch (Exception ignored) {
537 }
538 }
539 }
540
Chenbo Feng905f0342018-01-25 11:43:52 -0800541 private static long addIfSupported(long stat) {
542 return (stat == UNSUPPORTED) ? 0 : stat;
543 }
544
Jeff Sharkey7407e092011-07-19 23:47:12 -0700545 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700546 * Return number of packets transmitted across mobile networks since device
547 * boot. Counts packets across all mobile network interfaces, and always
548 * increases monotonically since device boot. Statistics are measured at the
549 * network layer, so they include both TCP and UDP usage.
550 * <p>
551 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
552 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800553 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700554 public static long getMobileTxPackets() {
555 long total = 0;
556 for (String iface : getMobileIfaces()) {
Chenbo Feng905f0342018-01-25 11:43:52 -0800557 total += addIfSupported(getTxPackets(iface));
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700558 }
559 return total;
560 }
Ken Shirriffae521152009-12-07 15:56:05 -0800561
562 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700563 * Return number of packets received across mobile networks since device
564 * boot. Counts packets across all mobile network interfaces, and always
565 * increases monotonically since device boot. Statistics are measured at the
566 * network layer, so they include both TCP and UDP usage.
567 * <p>
568 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
569 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800570 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700571 public static long getMobileRxPackets() {
572 long total = 0;
573 for (String iface : getMobileIfaces()) {
Chenbo Feng905f0342018-01-25 11:43:52 -0800574 total += addIfSupported(getRxPackets(iface));
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700575 }
576 return total;
577 }
Ken Shirriffae521152009-12-07 15:56:05 -0800578
579 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700580 * Return number of bytes transmitted across mobile networks since device
581 * boot. Counts packets across all mobile network interfaces, and always
582 * increases monotonically since device boot. Statistics are measured at the
583 * network layer, so they include both TCP and UDP usage.
584 * <p>
585 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
586 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800587 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700588 public static long getMobileTxBytes() {
589 long total = 0;
590 for (String iface : getMobileIfaces()) {
Chenbo Feng905f0342018-01-25 11:43:52 -0800591 total += addIfSupported(getTxBytes(iface));
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700592 }
593 return total;
594 }
Ken Shirriffae521152009-12-07 15:56:05 -0800595
596 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700597 * Return number of bytes received across mobile networks since device boot.
598 * Counts packets across all mobile network interfaces, and always increases
599 * monotonically since device boot. Statistics are measured at the network
600 * layer, so they include both TCP and UDP usage.
601 * <p>
602 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
603 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800604 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700605 public static long getMobileRxBytes() {
606 long total = 0;
607 for (String iface : getMobileIfaces()) {
Chenbo Feng905f0342018-01-25 11:43:52 -0800608 total += addIfSupported(getRxBytes(iface));
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700609 }
610 return total;
611 }
Ken Shirriffae521152009-12-07 15:56:05 -0800612
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800613 /** {@hide} */
Mathew Inwoodfe2fed72020-11-04 09:29:36 +0000614 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800615 public static long getMobileTcpRxPackets() {
616 long total = 0;
617 for (String iface : getMobileIfaces()) {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800618 long stat = UNSUPPORTED;
619 try {
620 stat = getStatsService().getIfaceStats(iface, TYPE_TCP_RX_PACKETS);
621 } catch (RemoteException e) {
622 throw e.rethrowFromSystemServer();
623 }
Chenbo Feng905f0342018-01-25 11:43:52 -0800624 total += addIfSupported(stat);
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800625 }
626 return total;
627 }
628
629 /** {@hide} */
Mathew Inwoodfe2fed72020-11-04 09:29:36 +0000630 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800631 public static long getMobileTcpTxPackets() {
632 long total = 0;
633 for (String iface : getMobileIfaces()) {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800634 long stat = UNSUPPORTED;
635 try {
636 stat = getStatsService().getIfaceStats(iface, TYPE_TCP_TX_PACKETS);
637 } catch (RemoteException e) {
638 throw e.rethrowFromSystemServer();
639 }
Chenbo Feng905f0342018-01-25 11:43:52 -0800640 total += addIfSupported(stat);
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800641 }
642 return total;
643 }
644
Aaron Huang443651d2019-09-27 22:31:22 +0800645 /**
junyulai3154d512020-09-29 14:19:24 +0800646 * Return the number of packets transmitted on the specified interface since the interface
647 * was created. Statistics are measured at the network layer, so both TCP and
Aaron Huang443651d2019-09-27 22:31:22 +0800648 * UDP usage are included.
649 *
junyulai3154d512020-09-29 14:19:24 +0800650 * Note that the returned values are partial statistics that do not count data from several
651 * sources and do not apply several adjustments that are necessary for correctness, such
652 * as adjusting for VPN apps, IPv6-in-IPv4 translation, etc. These values can be used to
653 * determine whether traffic is being transferred on the specific interface but are not a
654 * substitute for the more accurate statistics provided by the {@link NetworkStatsManager}
655 * APIs.
656 *
Aaron Huang443651d2019-09-27 22:31:22 +0800657 * @param iface The name of the interface.
658 * @return The number of transmitted packets.
659 */
660 public static long getTxPackets(@NonNull String iface) {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800661 try {
662 return getStatsService().getIfaceStats(iface, TYPE_TX_PACKETS);
663 } catch (RemoteException e) {
664 throw e.rethrowFromSystemServer();
665 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700666 }
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800667
Aaron Huang443651d2019-09-27 22:31:22 +0800668 /**
junyulai3154d512020-09-29 14:19:24 +0800669 * Return the number of packets received on the specified interface since the interface was
670 * created. Statistics are measured at the network layer, so both TCP
Aaron Huang443651d2019-09-27 22:31:22 +0800671 * and UDP usage are included.
672 *
junyulai3154d512020-09-29 14:19:24 +0800673 * Note that the returned values are partial statistics that do not count data from several
674 * sources and do not apply several adjustments that are necessary for correctness, such
675 * as adjusting for VPN apps, IPv6-in-IPv4 translation, etc. These values can be used to
676 * determine whether traffic is being transferred on the specific interface but are not a
677 * substitute for the more accurate statistics provided by the {@link NetworkStatsManager}
678 * APIs.
679 *
Aaron Huang443651d2019-09-27 22:31:22 +0800680 * @param iface The name of the interface.
681 * @return The number of received packets.
682 */
683 public static long getRxPackets(@NonNull String iface) {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800684 try {
685 return getStatsService().getIfaceStats(iface, TYPE_RX_PACKETS);
686 } catch (RemoteException e) {
687 throw e.rethrowFromSystemServer();
688 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700689 }
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800690
junyulai3154d512020-09-29 14:19:24 +0800691 /**
692 * Return the number of bytes transmitted on the specified interface since the interface
693 * was created. Statistics are measured at the network layer, so both TCP and
694 * UDP usage are included.
695 *
696 * Note that the returned values are partial statistics that do not count data from several
697 * sources and do not apply several adjustments that are necessary for correctness, such
698 * as adjusting for VPN apps, IPv6-in-IPv4 translation, etc. These values can be used to
699 * determine whether traffic is being transferred on the specific interface but are not a
700 * substitute for the more accurate statistics provided by the {@link NetworkStatsManager}
701 * APIs.
702 *
703 * @param iface The name of the interface.
704 * @return The number of transmitted bytes.
705 */
706 public static long getTxBytes(@NonNull String iface) {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800707 try {
708 return getStatsService().getIfaceStats(iface, TYPE_TX_BYTES);
709 } catch (RemoteException e) {
710 throw e.rethrowFromSystemServer();
711 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700712 }
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800713
junyulai3154d512020-09-29 14:19:24 +0800714 /**
715 * Return the number of bytes received on the specified interface since the interface
716 * was created. Statistics are measured at the network layer, so both TCP
717 * and UDP usage are included.
718 *
719 * Note that the returned values are partial statistics that do not count data from several
720 * sources and do not apply several adjustments that are necessary for correctness, such
721 * as adjusting for VPN apps, IPv6-in-IPv4 translation, etc. These values can be used to
722 * determine whether traffic is being transferred on the specific interface but are not a
723 * substitute for the more accurate statistics provided by the {@link NetworkStatsManager}
724 * APIs.
725 *
726 * @param iface The name of the interface.
727 * @return The number of received bytes.
728 */
729 public static long getRxBytes(@NonNull String iface) {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800730 try {
731 return getStatsService().getIfaceStats(iface, TYPE_RX_BYTES);
732 } catch (RemoteException e) {
733 throw e.rethrowFromSystemServer();
734 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700735 }
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800736
Benedict Wong083faee2017-12-03 19:42:36 -0800737 /** {@hide} */
738 @TestApi
739 public static long getLoopbackTxPackets() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800740 try {
741 return getStatsService().getIfaceStats(LOOPBACK_IFACE, TYPE_TX_PACKETS);
742 } catch (RemoteException e) {
743 throw e.rethrowFromSystemServer();
744 }
Benedict Wong083faee2017-12-03 19:42:36 -0800745 }
746
747 /** {@hide} */
748 @TestApi
749 public static long getLoopbackRxPackets() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800750 try {
751 return getStatsService().getIfaceStats(LOOPBACK_IFACE, TYPE_RX_PACKETS);
752 } catch (RemoteException e) {
753 throw e.rethrowFromSystemServer();
754 }
Benedict Wong083faee2017-12-03 19:42:36 -0800755 }
756
757 /** {@hide} */
758 @TestApi
759 public static long getLoopbackTxBytes() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800760 try {
761 return getStatsService().getIfaceStats(LOOPBACK_IFACE, TYPE_TX_BYTES);
762 } catch (RemoteException e) {
763 throw e.rethrowFromSystemServer();
764 }
Benedict Wong083faee2017-12-03 19:42:36 -0800765 }
766
767 /** {@hide} */
768 @TestApi
769 public static long getLoopbackRxBytes() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800770 try {
771 return getStatsService().getIfaceStats(LOOPBACK_IFACE, TYPE_RX_BYTES);
772 } catch (RemoteException e) {
773 throw e.rethrowFromSystemServer();
774 }
Benedict Wong083faee2017-12-03 19:42:36 -0800775 }
776
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800777 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700778 * Return number of packets transmitted since device boot. Counts packets
779 * across all network interfaces, and always increases monotonically since
780 * device boot. Statistics are measured at the network layer, so they
781 * include both TCP and UDP usage.
782 * <p>
783 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
784 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800785 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700786 public static long getTotalTxPackets() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800787 try {
788 return getStatsService().getTotalStats(TYPE_TX_PACKETS);
789 } catch (RemoteException e) {
790 throw e.rethrowFromSystemServer();
791 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700792 }
Ken Shirriffae521152009-12-07 15:56:05 -0800793
794 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700795 * Return number of packets received since device boot. Counts packets
796 * across all network interfaces, and always increases monotonically since
797 * device boot. Statistics are measured at the network layer, so they
798 * include both TCP and UDP usage.
799 * <p>
800 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
801 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800802 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700803 public static long getTotalRxPackets() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800804 try {
805 return getStatsService().getTotalStats(TYPE_RX_PACKETS);
806 } catch (RemoteException e) {
807 throw e.rethrowFromSystemServer();
808 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700809 }
Ken Shirriffae521152009-12-07 15:56:05 -0800810
811 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700812 * Return number of bytes transmitted since device boot. Counts packets
813 * across all network interfaces, and always increases monotonically since
814 * device boot. Statistics are measured at the network layer, so they
815 * include both TCP and UDP usage.
816 * <p>
817 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
818 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800819 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700820 public static long getTotalTxBytes() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800821 try {
822 return getStatsService().getTotalStats(TYPE_TX_BYTES);
823 } catch (RemoteException e) {
824 throw e.rethrowFromSystemServer();
825 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700826 }
Ken Shirriffae521152009-12-07 15:56:05 -0800827
828 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700829 * Return number of bytes received since device boot. Counts packets across
830 * all network interfaces, and always increases monotonically since device
831 * boot. Statistics are measured at the network layer, so they include both
832 * TCP and UDP usage.
833 * <p>
834 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
835 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800836 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700837 public static long getTotalRxBytes() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800838 try {
839 return getStatsService().getTotalStats(TYPE_RX_BYTES);
840 } catch (RemoteException e) {
841 throw e.rethrowFromSystemServer();
842 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700843 }
Ken Shirriffae521152009-12-07 15:56:05 -0800844
845 /**
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800846 * Return number of bytes transmitted by the given UID since device boot.
847 * Counts packets across all network interfaces, and always increases
848 * monotonically since device boot. Statistics are measured at the network
849 * layer, so they include both TCP and UDP usage.
850 * <p>
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700851 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
852 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
853 * <p>
854 * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
855 * report traffic statistics for the calling UID. It will return
856 * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
857 * historical network statistics belonging to other UIDs, use
858 * {@link NetworkStatsManager}.
Ken Shirriffae521152009-12-07 15:56:05 -0800859 *
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800860 * @see android.os.Process#myUid()
861 * @see android.content.pm.ApplicationInfo#uid
Ken Shirriffae521152009-12-07 15:56:05 -0800862 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800863 public static long getUidTxBytes(int uid) {
Chenbo Fengd80a6ed2019-06-17 16:22:28 -0700864 try {
865 return getStatsService().getUidStats(uid, TYPE_TX_BYTES);
866 } catch (RemoteException e) {
867 throw e.rethrowFromSystemServer();
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700868 }
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800869 }
Ken Shirriffae521152009-12-07 15:56:05 -0800870
871 /**
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800872 * Return number of bytes received by the given UID since device boot.
873 * Counts packets across all network interfaces, and always increases
874 * monotonically since device boot. Statistics are measured at the network
875 * layer, so they include both TCP and UDP usage.
876 * <p>
Dianne Hackborne9d72072013-02-25 15:55:37 -0800877 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800878 * {@link #UNSUPPORTED} on devices where statistics aren't available.
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700879 * <p>
880 * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
881 * report traffic statistics for the calling UID. It will return
882 * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
883 * historical network statistics belonging to other UIDs, use
884 * {@link NetworkStatsManager}.
Ken Shirriffae521152009-12-07 15:56:05 -0800885 *
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800886 * @see android.os.Process#myUid()
887 * @see android.content.pm.ApplicationInfo#uid
Ken Shirriffae521152009-12-07 15:56:05 -0800888 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800889 public static long getUidRxBytes(int uid) {
Chenbo Fengd80a6ed2019-06-17 16:22:28 -0700890 try {
891 return getStatsService().getUidStats(uid, TYPE_RX_BYTES);
892 } catch (RemoteException e) {
893 throw e.rethrowFromSystemServer();
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700894 }
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800895 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800896
897 /**
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800898 * Return number of packets transmitted by the given UID since device boot.
899 * Counts packets across all network interfaces, and always increases
900 * monotonically since device boot. Statistics are measured at the network
901 * layer, so they include both TCP and UDP usage.
902 * <p>
Dianne Hackborne9d72072013-02-25 15:55:37 -0800903 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800904 * {@link #UNSUPPORTED} on devices where statistics aren't available.
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700905 * <p>
906 * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
907 * report traffic statistics for the calling UID. It will return
908 * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
909 * historical network statistics belonging to other UIDs, use
910 * {@link NetworkStatsManager}.
Ashish Sharmadf852d82011-01-27 15:52:38 -0800911 *
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800912 * @see android.os.Process#myUid()
913 * @see android.content.pm.ApplicationInfo#uid
Ashish Sharmadf852d82011-01-27 15:52:38 -0800914 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800915 public static long getUidTxPackets(int uid) {
Chenbo Fengd80a6ed2019-06-17 16:22:28 -0700916 try {
917 return getStatsService().getUidStats(uid, TYPE_TX_PACKETS);
918 } catch (RemoteException e) {
919 throw e.rethrowFromSystemServer();
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700920 }
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800921 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800922
923 /**
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800924 * Return number of packets received by the given UID since device boot.
925 * Counts packets across all network interfaces, and always increases
926 * monotonically since device boot. Statistics are measured at the network
927 * layer, so they include both TCP and UDP usage.
928 * <p>
Dianne Hackborne9d72072013-02-25 15:55:37 -0800929 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800930 * {@link #UNSUPPORTED} on devices where statistics aren't available.
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700931 * <p>
932 * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
933 * report traffic statistics for the calling UID. It will return
934 * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
935 * historical network statistics belonging to other UIDs, use
936 * {@link NetworkStatsManager}.
Ashish Sharmadf852d82011-01-27 15:52:38 -0800937 *
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800938 * @see android.os.Process#myUid()
939 * @see android.content.pm.ApplicationInfo#uid
Ashish Sharmadf852d82011-01-27 15:52:38 -0800940 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800941 public static long getUidRxPackets(int uid) {
Chenbo Fengd80a6ed2019-06-17 16:22:28 -0700942 try {
943 return getStatsService().getUidStats(uid, TYPE_RX_PACKETS);
944 } catch (RemoteException e) {
945 throw e.rethrowFromSystemServer();
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700946 }
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800947 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800948
949 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -0800950 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800951 * transport layer statistics are no longer available, and will
952 * always return {@link #UNSUPPORTED}.
953 * @see #getUidTxBytes(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -0800954 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800955 @Deprecated
956 public static long getUidTcpTxBytes(int uid) {
957 return UNSUPPORTED;
958 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800959
960 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -0800961 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800962 * transport layer statistics are no longer available, and will
963 * always return {@link #UNSUPPORTED}.
964 * @see #getUidRxBytes(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -0800965 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800966 @Deprecated
967 public static long getUidTcpRxBytes(int uid) {
968 return UNSUPPORTED;
969 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800970
971 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -0800972 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800973 * transport layer statistics are no longer available, and will
974 * always return {@link #UNSUPPORTED}.
975 * @see #getUidTxBytes(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -0800976 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800977 @Deprecated
978 public static long getUidUdpTxBytes(int uid) {
979 return UNSUPPORTED;
980 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800981
982 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -0800983 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800984 * transport layer statistics are no longer available, and will
985 * always return {@link #UNSUPPORTED}.
986 * @see #getUidRxBytes(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -0800987 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800988 @Deprecated
989 public static long getUidUdpRxBytes(int uid) {
990 return UNSUPPORTED;
991 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800992
993 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -0800994 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800995 * transport layer statistics are no longer available, and will
996 * always return {@link #UNSUPPORTED}.
997 * @see #getUidTxPackets(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -0800998 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800999 @Deprecated
1000 public static long getUidTcpTxSegments(int uid) {
1001 return UNSUPPORTED;
1002 }
Ashish Sharmadf852d82011-01-27 15:52:38 -08001003
1004 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -08001005 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001006 * transport layer statistics are no longer available, and will
1007 * always return {@link #UNSUPPORTED}.
1008 * @see #getUidRxPackets(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -08001009 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001010 @Deprecated
1011 public static long getUidTcpRxSegments(int uid) {
1012 return UNSUPPORTED;
1013 }
Ashish Sharmadf852d82011-01-27 15:52:38 -08001014
Ashish Sharmadf852d82011-01-27 15:52:38 -08001015 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -08001016 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001017 * transport layer statistics are no longer available, and will
1018 * always return {@link #UNSUPPORTED}.
1019 * @see #getUidTxPackets(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -08001020 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001021 @Deprecated
1022 public static long getUidUdpTxPackets(int uid) {
1023 return UNSUPPORTED;
1024 }
Ashish Sharmadf852d82011-01-27 15:52:38 -08001025
1026 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -08001027 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001028 * transport layer statistics are no longer available, and will
1029 * always return {@link #UNSUPPORTED}.
1030 * @see #getUidRxPackets(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -08001031 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001032 @Deprecated
1033 public static long getUidUdpRxPackets(int uid) {
1034 return UNSUPPORTED;
1035 }
Jeff Sharkey33936ac2011-05-17 14:55:15 -07001036
1037 /**
1038 * Return detailed {@link NetworkStats} for the current UID. Requires no
1039 * special permission.
1040 */
Jeff Sharkey7407e092011-07-19 23:47:12 -07001041 private static NetworkStats getDataLayerSnapshotForUid(Context context) {
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -07001042 // TODO: take snapshot locally, since proc file is now visible
Jeff Sharkey33936ac2011-05-17 14:55:15 -07001043 final int uid = android.os.Process.myUid();
1044 try {
Jeff Sharkey8308b9b2012-04-10 19:48:07 -07001045 return getStatsService().getDataLayerSnapshotForUid(uid);
Jeff Sharkey33936ac2011-05-17 14:55:15 -07001046 } catch (RemoteException e) {
Jeff Sharkeybc08d072016-02-26 13:03:01 -07001047 throw e.rethrowFromSystemServer();
Jeff Sharkey33936ac2011-05-17 14:55:15 -07001048 }
1049 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -07001050
1051 /**
1052 * Return set of any ifaces associated with mobile networks since boot.
1053 * Interfaces are never removed from this list, so counters should always be
1054 * monotonic.
1055 */
Chalard Jean3cfb4992019-04-09 15:46:21 +09001056 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey8308b9b2012-04-10 19:48:07 -07001057 private static String[] getMobileIfaces() {
1058 try {
1059 return getStatsService().getMobileIfaces();
1060 } catch (RemoteException e) {
Jeff Sharkeybc08d072016-02-26 13:03:01 -07001061 throw e.rethrowFromSystemServer();
Jeff Sharkey8308b9b2012-04-10 19:48:07 -07001062 }
1063 }
1064
junyulaiea236322020-10-06 11:59:56 +08001065 // NOTE: keep these in sync with {@code com_android_server_net_NetworkStatsService.cpp}.
1066 /** {@hide} */
1067 public static final int TYPE_RX_BYTES = 0;
1068 /** {@hide} */
1069 public static final int TYPE_RX_PACKETS = 1;
1070 /** {@hide} */
1071 public static final int TYPE_TX_BYTES = 2;
1072 /** {@hide} */
1073 public static final int TYPE_TX_PACKETS = 3;
1074 /** {@hide} */
1075 public static final int TYPE_TCP_RX_PACKETS = 4;
1076 /** {@hide} */
1077 public static final int TYPE_TCP_TX_PACKETS = 5;
Ken Shirriffae521152009-12-07 15:56:05 -08001078}