blob: 032bc3f4023560a0db68d1db6b53cc37e29f04c5 [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
Aaron Huang443651d2019-09-27 22:31:22 +080019import android.annotation.NonNull;
Junyu Lai3f7bb332021-12-28 16:18:43 +000020import android.annotation.Nullable;
Jeff Sharkey1fb74312017-11-29 11:18:23 -070021import android.annotation.SuppressLint;
Christopher Tate5a1878d2014-08-06 14:19:56 -070022import android.annotation.SystemApi;
Benedict Wong083faee2017-12-03 19:42:36 -080023import android.annotation.TestApi;
Jeff Sharkey92790062011-06-24 17:05:24 -070024import android.app.DownloadManager;
25import android.app.backup.BackupManager;
Jeff Sharkey27c8a072016-03-09 16:40:15 -070026import android.app.usage.NetworkStatsManager;
Artur Satayev164c7562019-12-10 17:47:52 +000027import android.compat.annotation.UnsupportedAppUsage;
Jeff Sharkey33936ac2011-05-17 14:55:15 -070028import android.content.Context;
Jeff Sharkey92790062011-06-24 17:05:24 -070029import android.media.MediaPlayer;
Chalard Jean3cfb4992019-04-09 15:46:21 +090030import android.os.Build;
Junyu Lai3f7bb332021-12-28 16:18:43 +000031import android.os.IBinder;
Jeff Sharkey33936ac2011-05-17 14:55:15 -070032import android.os.RemoteException;
Jeff Sharkey33936ac2011-05-17 14:55:15 -070033
Jesse Wilsonb05f41c2011-06-28 19:06:31 -070034import com.android.server.NetworkManagementSocketTagger;
Ken Shirriffae521152009-12-07 15:56:05 -080035
Jesse Wilsonb05f41c2011-06-28 19:06:31 -070036import dalvik.system.SocketTagger;
Jeff Sharkey7407e092011-07-19 23:47:12 -070037
Jeff Sharkey1fb74312017-11-29 11:18:23 -070038import java.io.FileDescriptor;
39import java.io.IOException;
Junyu Lai3f7bb332021-12-28 16:18:43 +000040import java.lang.reflect.InvocationTargetException;
41import java.lang.reflect.Method;
Jeff Sharkey7b124cb2015-12-04 15:21:52 -070042import java.net.DatagramSocket;
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -070043import java.net.Socket;
44import java.net.SocketException;
Ken Shirriffae521152009-12-07 15:56:05 -080045
46/**
Jeff Sharkey27c8a072016-03-09 16:40:15 -070047 * Class that provides network traffic statistics. These statistics include
Dan Egnoreaeb7022010-04-07 17:30:50 -070048 * bytes transmitted and received and network packets transmitted and received,
49 * over all interfaces, over the mobile interface, and on a per-UID basis.
Ken Shirriffae521152009-12-07 15:56:05 -080050 * <p>
Jeff Sharkey27c8a072016-03-09 16:40:15 -070051 * These statistics may not be available on all platforms. If the statistics are
52 * not supported by this device, {@link #UNSUPPORTED} will be returned.
53 * <p>
54 * Note that the statistics returned by this class reset and start from zero
55 * after every reboot. To access more robust historical network statistics data,
56 * use {@link NetworkStatsManager} instead.
Ken Shirriffae521152009-12-07 15:56:05 -080057 */
58public class TrafficStats {
Junyu Lai3f7bb332021-12-28 16:18:43 +000059 private static final String TAG = TrafficStats.class.getSimpleName();
Ken Shirriffae521152009-12-07 15:56:05 -080060 /**
61 * The return value to indicate that the device does not support the statistic.
62 */
63 public final static int UNSUPPORTED = -1;
64
Junyu Lai1d3ce852021-12-27 13:56:59 +000065 /** @hide @deprecated use {@code DataUnit} instead to clarify SI-vs-IEC */
Jeff Sharkeya6886af2018-01-07 16:47:31 -070066 @Deprecated
Jeff Sharkey94a315c2012-02-03 14:50:07 -080067 public static final long KB_IN_BYTES = 1024;
Junyu Lai1d3ce852021-12-27 13:56:59 +000068 /** @hide @deprecated use {@code DataUnit} instead to clarify SI-vs-IEC */
Jeff Sharkeya6886af2018-01-07 16:47:31 -070069 @Deprecated
Jeff Sharkey94a315c2012-02-03 14:50:07 -080070 public static final long MB_IN_BYTES = KB_IN_BYTES * 1024;
Junyu Lai1d3ce852021-12-27 13:56:59 +000071 /** @hide @deprecated use {@code DataUnit} instead to clarify SI-vs-IEC */
Jeff Sharkeya6886af2018-01-07 16:47:31 -070072 @Deprecated
Jeff Sharkey94a315c2012-02-03 14:50:07 -080073 public static final long GB_IN_BYTES = MB_IN_BYTES * 1024;
Junyu Lai1d3ce852021-12-27 13:56:59 +000074 /** @hide @deprecated use {@code DataUnit} instead to clarify SI-vs-IEC */
Jeff Sharkeya6886af2018-01-07 16:47:31 -070075 @Deprecated
Jeff Sharkey6f2ba5e2015-03-18 11:27:19 -070076 public static final long TB_IN_BYTES = GB_IN_BYTES * 1024;
Junyu Lai1d3ce852021-12-27 13:56:59 +000077 /** @hide @deprecated use {@code DataUnit} instead to clarify SI-vs-IEC */
Jeff Sharkeya6886af2018-01-07 16:47:31 -070078 @Deprecated
Jeff Sharkey88069072015-06-15 21:09:10 -070079 public static final long PB_IN_BYTES = TB_IN_BYTES * 1024;
Jeff Sharkey94a315c2012-02-03 14:50:07 -080080
Jeff Sharkey1a3eb882011-05-28 20:56:34 -070081 /**
Jeff Sharkeyc04cda62011-06-19 01:08:12 -070082 * Special UID value used when collecting {@link NetworkStatsHistory} for
83 * removed applications.
84 *
85 * @hide
86 */
87 public static final int UID_REMOVED = -4;
88
89 /**
Jeff Sharkey987f5ff2011-09-16 01:52:49 -070090 * Special UID value used when collecting {@link NetworkStatsHistory} for
91 * tethering traffic.
92 *
93 * @hide
94 */
junyulai55041a42019-11-15 17:15:01 +080095 public static final int UID_TETHERING = NetworkStats.UID_TETHERING;
Jeff Sharkey987f5ff2011-09-16 01:52:49 -070096
97 /**
Chalard Jean8a93ab82019-04-09 11:16:56 +090098 * Tag values in this range are reserved for the network stack. The network stack is
99 * running as UID {@link android.os.Process.NETWORK_STACK_UID} when in the mainline
100 * module separate process, and as the system UID otherwise.
101 */
102 /** @hide */
103 @SystemApi
104 public static final int TAG_NETWORK_STACK_RANGE_START = 0xFFFFFD00;
105 /** @hide */
106 @SystemApi
107 public static final int TAG_NETWORK_STACK_RANGE_END = 0xFFFFFEFF;
108
109 /**
110 * Tags between 0xFFFFFF00 and 0xFFFFFFFF are reserved and used internally by system services
111 * like DownloadManager when performing traffic on behalf of an application.
112 */
113 // Please note there is no enforcement of these constants, so do not rely on them to
114 // determine that the caller is a system caller.
115 /** @hide */
116 @SystemApi
117 public static final int TAG_SYSTEM_IMPERSONATION_RANGE_START = 0xFFFFFF00;
118 /** @hide */
119 @SystemApi
120 public static final int TAG_SYSTEM_IMPERSONATION_RANGE_END = 0xFFFFFF0F;
121
122 /**
123 * Tag values between these ranges are reserved for the network stack to do traffic
124 * on behalf of applications. It is a subrange of the range above.
125 */
126 /** @hide */
127 @SystemApi
128 public static final int TAG_NETWORK_STACK_IMPERSONATION_RANGE_START = 0xFFFFFF80;
129 /** @hide */
130 @SystemApi
131 public static final int TAG_NETWORK_STACK_IMPERSONATION_RANGE_END = 0xFFFFFF8F;
132
133 /**
Jeff Sharkey92790062011-06-24 17:05:24 -0700134 * Default tag value for {@link DownloadManager} traffic.
135 *
136 * @hide
137 */
Jeff Sharkey987f5ff2011-09-16 01:52:49 -0700138 public static final int TAG_SYSTEM_DOWNLOAD = 0xFFFFFF01;
Jeff Sharkey92790062011-06-24 17:05:24 -0700139
140 /**
141 * Default tag value for {@link MediaPlayer} traffic.
142 *
143 * @hide
144 */
Jeff Sharkey987f5ff2011-09-16 01:52:49 -0700145 public static final int TAG_SYSTEM_MEDIA = 0xFFFFFF02;
Jeff Sharkey92790062011-06-24 17:05:24 -0700146
147 /**
Christopher Tatec1c71fd2015-11-10 10:49:20 -0800148 * Default tag value for {@link BackupManager} backup traffic; that is,
149 * traffic from the device to the storage backend.
Jeff Sharkey92790062011-06-24 17:05:24 -0700150 *
151 * @hide
152 */
Jeff Sharkey987f5ff2011-09-16 01:52:49 -0700153 public static final int TAG_SYSTEM_BACKUP = 0xFFFFFF03;
Jeff Sharkey92790062011-06-24 17:05:24 -0700154
Christopher Tatec1c71fd2015-11-10 10:49:20 -0800155 /**
156 * Default tag value for {@link BackupManager} restore traffic; that is,
157 * app data retrieved from the storage backend at install time.
158 *
159 * @hide
160 */
161 public static final int TAG_SYSTEM_RESTORE = 0xFFFFFF04;
162
Jeff Sharkey66dca172016-11-21 12:14:50 -0700163 /**
Jeff Sharkeyb1f97ac2017-08-11 15:04:12 -0600164 * Default tag value for code (typically APKs) downloaded by an app store on
165 * behalf of the app, such as updates.
Jeff Sharkey66dca172016-11-21 12:14:50 -0700166 *
167 * @hide
168 */
Jeff Sharkeyb1f97ac2017-08-11 15:04:12 -0600169 public static final int TAG_SYSTEM_APP = 0xFFFFFF05;
Jeff Sharkey8af5ad12017-06-26 19:50:41 -0600170
Chalard Jean8a93ab82019-04-09 11:16:56 +0900171 // TODO : remove this constant when Wifi code is updated
Jeff Sharkey8af5ad12017-06-26 19:50:41 -0600172 /** @hide */
Jeff Sharkey8af5ad12017-06-26 19:50:41 -0600173 public static final int TAG_SYSTEM_PROBE = 0xFFFFFF42;
Jeff Sharkey66dca172016-11-21 12:14:50 -0700174
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700175 private static INetworkStatsService sStatsService;
176
Chalard Jean3cfb4992019-04-09 15:46:21 +0900177 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700178 private synchronized static INetworkStatsService getStatsService() {
179 if (sStatsService == null) {
Junyu Lai3f7bb332021-12-28 16:18:43 +0000180 sStatsService = getStatsBinder();
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700181 }
182 return sStatsService;
183 }
184
Junyu Lai3f7bb332021-12-28 16:18:43 +0000185 @Nullable
186 private static INetworkStatsService getStatsBinder() {
187 try {
188 final Method getServiceMethod = Class.forName("android.os.ServiceManager")
189 .getDeclaredMethod("getService", new Class[]{String.class});
190 final IBinder binder = (IBinder) getServiceMethod.invoke(
191 null, Context.NETWORK_STATS_SERVICE);
192 return INetworkStatsService.Stub.asInterface(binder);
193 } catch (NoSuchMethodException | ClassNotFoundException | IllegalAccessException
194 | InvocationTargetException e) {
195 throw new NullPointerException("Cannot get INetworkStatsService: " + e);
196 }
197 }
198
Jeff Sharkey92790062011-06-24 17:05:24 -0700199 /**
Jeff Sharkey33936ac2011-05-17 14:55:15 -0700200 * Snapshot of {@link NetworkStats} when the currently active profiling
201 * session started, or {@code null} if no session active.
202 *
203 * @see #startDataProfiling(Context)
204 * @see #stopDataProfiling(Context)
205 */
206 private static NetworkStats sActiveProfilingStart;
207
208 private static Object sProfilingLock = new Object();
209
Benedict Wong083faee2017-12-03 19:42:36 -0800210 private static final String LOOPBACK_IFACE = "lo";
211
Jeff Sharkey33936ac2011-05-17 14:55:15 -0700212 /**
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700213 * Set active tag to use when accounting {@link Socket} traffic originating
214 * from the current thread. Only one active tag per thread is supported.
215 * <p>
216 * Changes only take effect during subsequent calls to
217 * {@link #tagSocket(Socket)}.
Jeff Sharkey987f5ff2011-09-16 01:52:49 -0700218 * <p>
219 * Tags between {@code 0xFFFFFF00} and {@code 0xFFFFFFFF} are reserved and
220 * used internally by system services like {@link DownloadManager} when
221 * performing traffic on behalf of an application.
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700222 *
223 * @see #clearThreadStatsTag()
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700224 */
Jeff Sharkey92790062011-06-24 17:05:24 -0700225 public static void setThreadStatsTag(int tag) {
Jesse Wilsonb05f41c2011-06-28 19:06:31 -0700226 NetworkManagementSocketTagger.setThreadSocketStatsTag(tag);
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700227 }
228
Jeff Sharkey92790062011-06-24 17:05:24 -0700229 /**
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600230 * Set active tag to use when accounting {@link Socket} traffic originating
Jeff Sharkey289eac12017-01-19 11:55:54 -0700231 * from the current thread. Only one active tag per thread is supported.
232 * <p>
233 * Changes only take effect during subsequent calls to
234 * {@link #tagSocket(Socket)}.
235 * <p>
236 * Tags between {@code 0xFFFFFF00} and {@code 0xFFFFFFFF} are reserved and
237 * used internally by system services like {@link DownloadManager} when
238 * performing traffic on behalf of an application.
239 *
240 * @return the current tag for the calling thread, which can be used to
241 * restore any existing values after a nested operation is finished
242 */
243 public static int getAndSetThreadStatsTag(int tag) {
244 return NetworkManagementSocketTagger.setThreadSocketStatsTag(tag);
245 }
246
247 /**
248 * Set active tag to use when accounting {@link Socket} traffic originating
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600249 * from the current thread. The tag used internally is well-defined to
250 * distinguish all backup-related traffic.
251 *
Christopher Tate5a1878d2014-08-06 14:19:56 -0700252 * @hide
253 */
254 @SystemApi
255 public static void setThreadStatsTagBackup() {
256 setThreadStatsTag(TAG_SYSTEM_BACKUP);
257 }
258
259 /**
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600260 * Set active tag to use when accounting {@link Socket} traffic originating
261 * from the current thread. The tag used internally is well-defined to
262 * distinguish all restore-related traffic.
263 *
Christopher Tatec1c71fd2015-11-10 10:49:20 -0800264 * @hide
265 */
266 @SystemApi
267 public static void setThreadStatsTagRestore() {
268 setThreadStatsTag(TAG_SYSTEM_RESTORE);
269 }
270
271 /**
Jeff Sharkey8af5ad12017-06-26 19:50:41 -0600272 * Set active tag to use when accounting {@link Socket} traffic originating
273 * from the current thread. The tag used internally is well-defined to
Jeff Sharkeyb1f97ac2017-08-11 15:04:12 -0600274 * distinguish all code (typically APKs) downloaded by an app store on
275 * behalf of the app, such as updates.
Jeff Sharkey8af5ad12017-06-26 19:50:41 -0600276 *
277 * @hide
278 */
279 @SystemApi
Jeff Sharkeyb1f97ac2017-08-11 15:04:12 -0600280 public static void setThreadStatsTagApp() {
281 setThreadStatsTag(TAG_SYSTEM_APP);
Jeff Sharkey8af5ad12017-06-26 19:50:41 -0600282 }
283
284 /**
Alon Albert2c295f02011-07-19 11:16:09 +0300285 * Get the active tag used when accounting {@link Socket} traffic originating
286 * from the current thread. Only one active tag per thread is supported.
287 * {@link #tagSocket(Socket)}.
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700288 *
289 * @see #setThreadStatsTag(int)
Alon Albert2c295f02011-07-19 11:16:09 +0300290 */
291 public static int getThreadStatsTag() {
292 return NetworkManagementSocketTagger.getThreadSocketStatsTag();
293 }
294
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700295 /**
296 * Clear any active tag set to account {@link Socket} traffic originating
297 * from the current thread.
298 *
299 * @see #setThreadStatsTag(int)
300 */
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700301 public static void clearThreadStatsTag() {
Jesse Wilsonb05f41c2011-06-28 19:06:31 -0700302 NetworkManagementSocketTagger.setThreadSocketStatsTag(-1);
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700303 }
304
305 /**
306 * Set specific UID to use when accounting {@link Socket} traffic
307 * originating from the current thread. Designed for use when performing an
Jeff Sharkey17a38752018-03-26 13:11:33 -0600308 * operation on behalf of another application, or when another application
309 * is performing operations on your behalf.
310 * <p>
311 * Any app can <em>accept</em> blame for traffic performed on a socket
312 * originally created by another app by calling this method with the
313 * {@link android.system.Os#getuid()} value. However, only apps holding the
314 * {@code android.Manifest.permission#UPDATE_DEVICE_STATS} permission may
315 * <em>assign</em> blame to another UIDs.
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700316 * <p>
317 * Changes only take effect during subsequent calls to
318 * {@link #tagSocket(Socket)}.
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700319 */
Aurimas Liutikas9de1e0e2020-11-12 18:29:11 -0800320 @SuppressLint("RequiresPermission")
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700321 public static void setThreadStatsUid(int uid) {
Jesse Wilsonb05f41c2011-06-28 19:06:31 -0700322 NetworkManagementSocketTagger.setThreadSocketStatsUid(uid);
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700323 }
324
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600325 /**
Jeff Sharkey17a38752018-03-26 13:11:33 -0600326 * Get the active UID used when accounting {@link Socket} traffic originating
327 * from the current thread. Only one active tag per thread is supported.
328 * {@link #tagSocket(Socket)}.
329 *
330 * @see #setThreadStatsUid(int)
331 */
332 public static int getThreadStatsUid() {
333 return NetworkManagementSocketTagger.getThreadSocketStatsUid();
334 }
335
336 /**
Jeff Sharkey1fb74312017-11-29 11:18:23 -0700337 * Set specific UID to use when accounting {@link Socket} traffic
338 * originating from the current thread as the calling UID. Designed for use
339 * when another application is performing operations on your behalf.
340 * <p>
341 * Changes only take effect during subsequent calls to
342 * {@link #tagSocket(Socket)}.
Jeff Sharkey17a38752018-03-26 13:11:33 -0600343 *
344 * @removed
345 * @deprecated use {@link #setThreadStatsUid(int)} instead.
Jeff Sharkey1fb74312017-11-29 11:18:23 -0700346 */
Jeff Sharkey17a38752018-03-26 13:11:33 -0600347 @Deprecated
Jeff Sharkey1fb74312017-11-29 11:18:23 -0700348 public static void setThreadStatsUidSelf() {
349 setThreadStatsUid(android.os.Process.myUid());
350 }
351
352 /**
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600353 * Clear any active UID set to account {@link Socket} traffic originating
354 * from the current thread.
355 *
356 * @see #setThreadStatsUid(int)
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600357 */
Aurimas Liutikas9de1e0e2020-11-12 18:29:11 -0800358 @SuppressLint("RequiresPermission")
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700359 public static void clearThreadStatsUid() {
Jesse Wilsonb05f41c2011-06-28 19:06:31 -0700360 NetworkManagementSocketTagger.setThreadSocketStatsUid(-1);
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700361 }
362
363 /**
364 * Tag the given {@link Socket} with any statistics parameters active for
365 * the current thread. Subsequent calls always replace any existing
366 * parameters. When finished, call {@link #untagSocket(Socket)} to remove
367 * statistics parameters.
368 *
Jeff Sharkey92790062011-06-24 17:05:24 -0700369 * @see #setThreadStatsTag(int)
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700370 */
371 public static void tagSocket(Socket socket) throws SocketException {
Jesse Wilsonb05f41c2011-06-28 19:06:31 -0700372 SocketTagger.get().tag(socket);
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700373 }
374
375 /**
376 * Remove any statistics parameters from the given {@link Socket}.
koprivac134e242018-07-23 18:19:39 -0700377 * <p>
378 * In Android 8.1 (API level 27) and lower, a socket is automatically
379 * untagged when it's sent to another process using binder IPC with a
380 * {@code ParcelFileDescriptor} container. In Android 9.0 (API level 28)
381 * and higher, the socket tag is kept when the socket is sent to another
382 * process using binder IPC. You can mimic the previous behavior by
383 * calling {@code untagSocket()} before sending the socket to another
384 * process.
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700385 */
386 public static void untagSocket(Socket socket) throws SocketException {
Jesse Wilsonb05f41c2011-06-28 19:06:31 -0700387 SocketTagger.get().untag(socket);
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700388 }
389
390 /**
Jeff Sharkey7b124cb2015-12-04 15:21:52 -0700391 * Tag the given {@link DatagramSocket} with any statistics parameters
392 * active for the current thread. Subsequent calls always replace any
393 * existing parameters. When finished, call
394 * {@link #untagDatagramSocket(DatagramSocket)} to remove statistics
395 * parameters.
396 *
397 * @see #setThreadStatsTag(int)
Jeff Sharkey7b124cb2015-12-04 15:21:52 -0700398 */
399 public static void tagDatagramSocket(DatagramSocket socket) throws SocketException {
400 SocketTagger.get().tag(socket);
401 }
402
403 /**
404 * Remove any statistics parameters from the given {@link DatagramSocket}.
405 */
406 public static void untagDatagramSocket(DatagramSocket socket) throws SocketException {
407 SocketTagger.get().untag(socket);
408 }
409
410 /**
Jeff Sharkey1fb74312017-11-29 11:18:23 -0700411 * Tag the given {@link FileDescriptor} socket with any statistics
412 * parameters active for the current thread. Subsequent calls always replace
413 * any existing parameters. When finished, call
414 * {@link #untagFileDescriptor(FileDescriptor)} to remove statistics
415 * parameters.
416 *
417 * @see #setThreadStatsTag(int)
418 */
419 public static void tagFileDescriptor(FileDescriptor fd) throws IOException {
420 SocketTagger.get().tag(fd);
421 }
422
423 /**
424 * Remove any statistics parameters from the given {@link FileDescriptor}
425 * socket.
426 */
427 public static void untagFileDescriptor(FileDescriptor fd) throws IOException {
428 SocketTagger.get().untag(fd);
429 }
430
431 /**
Jeff Sharkey33936ac2011-05-17 14:55:15 -0700432 * Start profiling data usage for current UID. Only one profiling session
433 * can be active at a time.
434 *
435 * @hide
436 */
437 public static void startDataProfiling(Context context) {
438 synchronized (sProfilingLock) {
439 if (sActiveProfilingStart != null) {
440 throw new IllegalStateException("already profiling data");
441 }
442
443 // take snapshot in time; we calculate delta later
Jeff Sharkey7407e092011-07-19 23:47:12 -0700444 sActiveProfilingStart = getDataLayerSnapshotForUid(context);
Jeff Sharkey33936ac2011-05-17 14:55:15 -0700445 }
446 }
447
448 /**
449 * Stop profiling data usage for current UID.
450 *
451 * @return Detailed {@link NetworkStats} of data that occurred since last
452 * {@link #startDataProfiling(Context)} call.
453 * @hide
454 */
455 public static NetworkStats stopDataProfiling(Context context) {
456 synchronized (sProfilingLock) {
457 if (sActiveProfilingStart == null) {
458 throw new IllegalStateException("not profiling data");
459 }
460
Jeff Sharkeyef7bded2012-01-10 17:24:44 -0800461 // subtract starting values and return delta
462 final NetworkStats profilingStop = getDataLayerSnapshotForUid(context);
463 final NetworkStats profilingDelta = NetworkStats.subtract(
Jeff Sharkeybfe82682012-01-11 18:38:16 -0800464 profilingStop, sActiveProfilingStart, null, null);
Jeff Sharkeyef7bded2012-01-10 17:24:44 -0800465 sActiveProfilingStart = null;
466 return profilingDelta;
Jeff Sharkey33936ac2011-05-17 14:55:15 -0700467 }
468 }
469
470 /**
Jeff Sharkey60ca0232011-08-24 15:42:09 -0700471 * Increment count of network operations performed under the accounting tag
472 * currently active on the calling thread. This can be used to derive
473 * bytes-per-operation.
474 *
475 * @param operationCount Number of operations to increment count by.
476 */
477 public static void incrementOperationCount(int operationCount) {
478 final int tag = getThreadStatsTag();
479 incrementOperationCount(tag, operationCount);
480 }
481
482 /**
Jeff Sharkey7407e092011-07-19 23:47:12 -0700483 * Increment count of network operations performed under the given
484 * accounting tag. This can be used to derive bytes-per-operation.
485 *
486 * @param tag Accounting tag used in {@link #setThreadStatsTag(int)}.
487 * @param operationCount Number of operations to increment count by.
488 */
489 public static void incrementOperationCount(int tag, int operationCount) {
Jeff Sharkey7407e092011-07-19 23:47:12 -0700490 final int uid = android.os.Process.myUid();
491 try {
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700492 getStatsService().incrementOperationCount(uid, tag, operationCount);
Jeff Sharkey7407e092011-07-19 23:47:12 -0700493 } catch (RemoteException e) {
Jeff Sharkeybc08d072016-02-26 13:03:01 -0700494 throw e.rethrowFromSystemServer();
Jeff Sharkey7407e092011-07-19 23:47:12 -0700495 }
496 }
497
Jeff Sharkey920d9042012-04-06 11:12:08 -0700498 /** {@hide} */
499 public static void closeQuietly(INetworkStatsSession session) {
500 // TODO: move to NetworkStatsService once it exists
501 if (session != null) {
502 try {
503 session.close();
504 } catch (RuntimeException rethrown) {
505 throw rethrown;
506 } catch (Exception ignored) {
507 }
508 }
509 }
510
Chenbo Feng905f0342018-01-25 11:43:52 -0800511 private static long addIfSupported(long stat) {
512 return (stat == UNSUPPORTED) ? 0 : stat;
513 }
514
Jeff Sharkey7407e092011-07-19 23:47:12 -0700515 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700516 * Return number of packets transmitted across mobile networks since device
517 * boot. Counts packets across all mobile network interfaces, and always
518 * increases monotonically since device boot. Statistics are measured at the
519 * network layer, so they include both TCP and UDP usage.
520 * <p>
521 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
522 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800523 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700524 public static long getMobileTxPackets() {
525 long total = 0;
526 for (String iface : getMobileIfaces()) {
Chenbo Feng905f0342018-01-25 11:43:52 -0800527 total += addIfSupported(getTxPackets(iface));
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700528 }
529 return total;
530 }
Ken Shirriffae521152009-12-07 15:56:05 -0800531
532 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700533 * Return number of packets received across mobile networks since device
534 * boot. Counts packets across all mobile network interfaces, and always
535 * increases monotonically since device boot. Statistics are measured at the
536 * network layer, so they include both TCP and UDP usage.
537 * <p>
538 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
539 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800540 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700541 public static long getMobileRxPackets() {
542 long total = 0;
543 for (String iface : getMobileIfaces()) {
Chenbo Feng905f0342018-01-25 11:43:52 -0800544 total += addIfSupported(getRxPackets(iface));
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700545 }
546 return total;
547 }
Ken Shirriffae521152009-12-07 15:56:05 -0800548
549 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700550 * Return number of bytes transmitted across mobile networks since device
551 * boot. Counts packets across all mobile network interfaces, and always
552 * increases monotonically since device boot. Statistics are measured at the
553 * network layer, so they include both TCP and UDP usage.
554 * <p>
555 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
556 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800557 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700558 public static long getMobileTxBytes() {
559 long total = 0;
560 for (String iface : getMobileIfaces()) {
Chenbo Feng905f0342018-01-25 11:43:52 -0800561 total += addIfSupported(getTxBytes(iface));
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700562 }
563 return total;
564 }
Ken Shirriffae521152009-12-07 15:56:05 -0800565
566 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700567 * Return number of bytes received across mobile networks since device boot.
568 * Counts packets across all mobile network interfaces, and always increases
569 * monotonically since device boot. Statistics are measured at the network
570 * layer, so they include both TCP and UDP usage.
571 * <p>
572 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
573 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800574 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700575 public static long getMobileRxBytes() {
576 long total = 0;
577 for (String iface : getMobileIfaces()) {
Chenbo Feng905f0342018-01-25 11:43:52 -0800578 total += addIfSupported(getRxBytes(iface));
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700579 }
580 return total;
581 }
Ken Shirriffae521152009-12-07 15:56:05 -0800582
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800583 /** {@hide} */
Mathew Inwoodfe2fed72020-11-04 09:29:36 +0000584 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800585 public static long getMobileTcpRxPackets() {
586 long total = 0;
587 for (String iface : getMobileIfaces()) {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800588 long stat = UNSUPPORTED;
589 try {
590 stat = getStatsService().getIfaceStats(iface, TYPE_TCP_RX_PACKETS);
591 } catch (RemoteException e) {
592 throw e.rethrowFromSystemServer();
593 }
Chenbo Feng905f0342018-01-25 11:43:52 -0800594 total += addIfSupported(stat);
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800595 }
596 return total;
597 }
598
599 /** {@hide} */
Mathew Inwoodfe2fed72020-11-04 09:29:36 +0000600 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800601 public static long getMobileTcpTxPackets() {
602 long total = 0;
603 for (String iface : getMobileIfaces()) {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800604 long stat = UNSUPPORTED;
605 try {
606 stat = getStatsService().getIfaceStats(iface, TYPE_TCP_TX_PACKETS);
607 } catch (RemoteException e) {
608 throw e.rethrowFromSystemServer();
609 }
Chenbo Feng905f0342018-01-25 11:43:52 -0800610 total += addIfSupported(stat);
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800611 }
612 return total;
613 }
614
Aaron Huang443651d2019-09-27 22:31:22 +0800615 /**
junyulai3154d512020-09-29 14:19:24 +0800616 * Return the number of packets transmitted on the specified interface since the interface
617 * was created. Statistics are measured at the network layer, so both TCP and
Aaron Huang443651d2019-09-27 22:31:22 +0800618 * UDP usage are included.
619 *
junyulai3154d512020-09-29 14:19:24 +0800620 * Note that the returned values are partial statistics that do not count data from several
621 * sources and do not apply several adjustments that are necessary for correctness, such
622 * as adjusting for VPN apps, IPv6-in-IPv4 translation, etc. These values can be used to
623 * determine whether traffic is being transferred on the specific interface but are not a
624 * substitute for the more accurate statistics provided by the {@link NetworkStatsManager}
625 * APIs.
626 *
Aaron Huang443651d2019-09-27 22:31:22 +0800627 * @param iface The name of the interface.
628 * @return The number of transmitted packets.
629 */
630 public static long getTxPackets(@NonNull String iface) {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800631 try {
632 return getStatsService().getIfaceStats(iface, TYPE_TX_PACKETS);
633 } catch (RemoteException e) {
634 throw e.rethrowFromSystemServer();
635 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700636 }
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800637
Aaron Huang443651d2019-09-27 22:31:22 +0800638 /**
junyulai3154d512020-09-29 14:19:24 +0800639 * Return the number of packets received on the specified interface since the interface was
640 * created. Statistics are measured at the network layer, so both TCP
Aaron Huang443651d2019-09-27 22:31:22 +0800641 * and UDP usage are included.
642 *
junyulai3154d512020-09-29 14:19:24 +0800643 * Note that the returned values are partial statistics that do not count data from several
644 * sources and do not apply several adjustments that are necessary for correctness, such
645 * as adjusting for VPN apps, IPv6-in-IPv4 translation, etc. These values can be used to
646 * determine whether traffic is being transferred on the specific interface but are not a
647 * substitute for the more accurate statistics provided by the {@link NetworkStatsManager}
648 * APIs.
649 *
Aaron Huang443651d2019-09-27 22:31:22 +0800650 * @param iface The name of the interface.
651 * @return The number of received packets.
652 */
653 public static long getRxPackets(@NonNull String iface) {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800654 try {
655 return getStatsService().getIfaceStats(iface, TYPE_RX_PACKETS);
656 } catch (RemoteException e) {
657 throw e.rethrowFromSystemServer();
658 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700659 }
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800660
junyulai3154d512020-09-29 14:19:24 +0800661 /**
662 * Return the number of bytes transmitted on the specified interface since the interface
663 * was created. Statistics are measured at the network layer, so both TCP and
664 * UDP usage are included.
665 *
666 * Note that the returned values are partial statistics that do not count data from several
667 * sources and do not apply several adjustments that are necessary for correctness, such
668 * as adjusting for VPN apps, IPv6-in-IPv4 translation, etc. These values can be used to
669 * determine whether traffic is being transferred on the specific interface but are not a
670 * substitute for the more accurate statistics provided by the {@link NetworkStatsManager}
671 * APIs.
672 *
673 * @param iface The name of the interface.
674 * @return The number of transmitted bytes.
675 */
676 public static long getTxBytes(@NonNull String iface) {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800677 try {
678 return getStatsService().getIfaceStats(iface, TYPE_TX_BYTES);
679 } catch (RemoteException e) {
680 throw e.rethrowFromSystemServer();
681 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700682 }
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800683
junyulai3154d512020-09-29 14:19:24 +0800684 /**
685 * Return the number of bytes received on the specified interface since the interface
686 * was created. Statistics are measured at the network layer, so both TCP
687 * and UDP usage are included.
688 *
689 * Note that the returned values are partial statistics that do not count data from several
690 * sources and do not apply several adjustments that are necessary for correctness, such
691 * as adjusting for VPN apps, IPv6-in-IPv4 translation, etc. These values can be used to
692 * determine whether traffic is being transferred on the specific interface but are not a
693 * substitute for the more accurate statistics provided by the {@link NetworkStatsManager}
694 * APIs.
695 *
696 * @param iface The name of the interface.
697 * @return The number of received bytes.
698 */
699 public static long getRxBytes(@NonNull String iface) {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800700 try {
701 return getStatsService().getIfaceStats(iface, TYPE_RX_BYTES);
702 } catch (RemoteException e) {
703 throw e.rethrowFromSystemServer();
704 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700705 }
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800706
Benedict Wong083faee2017-12-03 19:42:36 -0800707 /** {@hide} */
708 @TestApi
709 public static long getLoopbackTxPackets() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800710 try {
711 return getStatsService().getIfaceStats(LOOPBACK_IFACE, TYPE_TX_PACKETS);
712 } catch (RemoteException e) {
713 throw e.rethrowFromSystemServer();
714 }
Benedict Wong083faee2017-12-03 19:42:36 -0800715 }
716
717 /** {@hide} */
718 @TestApi
719 public static long getLoopbackRxPackets() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800720 try {
721 return getStatsService().getIfaceStats(LOOPBACK_IFACE, TYPE_RX_PACKETS);
722 } catch (RemoteException e) {
723 throw e.rethrowFromSystemServer();
724 }
Benedict Wong083faee2017-12-03 19:42:36 -0800725 }
726
727 /** {@hide} */
728 @TestApi
729 public static long getLoopbackTxBytes() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800730 try {
731 return getStatsService().getIfaceStats(LOOPBACK_IFACE, TYPE_TX_BYTES);
732 } catch (RemoteException e) {
733 throw e.rethrowFromSystemServer();
734 }
Benedict Wong083faee2017-12-03 19:42:36 -0800735 }
736
737 /** {@hide} */
738 @TestApi
739 public static long getLoopbackRxBytes() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800740 try {
741 return getStatsService().getIfaceStats(LOOPBACK_IFACE, TYPE_RX_BYTES);
742 } catch (RemoteException e) {
743 throw e.rethrowFromSystemServer();
744 }
Benedict Wong083faee2017-12-03 19:42:36 -0800745 }
746
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800747 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700748 * Return number of packets transmitted since device boot. Counts packets
749 * across all network interfaces, and always increases monotonically since
750 * device boot. Statistics are measured at the network layer, so they
751 * include both TCP and UDP usage.
752 * <p>
753 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
754 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800755 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700756 public static long getTotalTxPackets() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800757 try {
758 return getStatsService().getTotalStats(TYPE_TX_PACKETS);
759 } catch (RemoteException e) {
760 throw e.rethrowFromSystemServer();
761 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700762 }
Ken Shirriffae521152009-12-07 15:56:05 -0800763
764 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700765 * Return number of packets received since device boot. Counts packets
766 * across all network interfaces, and always increases monotonically since
767 * device boot. Statistics are measured at the network layer, so they
768 * include both TCP and UDP usage.
769 * <p>
770 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
771 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800772 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700773 public static long getTotalRxPackets() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800774 try {
775 return getStatsService().getTotalStats(TYPE_RX_PACKETS);
776 } catch (RemoteException e) {
777 throw e.rethrowFromSystemServer();
778 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700779 }
Ken Shirriffae521152009-12-07 15:56:05 -0800780
781 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700782 * Return number of bytes transmitted since device boot. Counts packets
783 * across all network interfaces, and always increases monotonically since
784 * device boot. Statistics are measured at the network layer, so they
785 * include both TCP and UDP usage.
786 * <p>
787 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
788 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800789 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700790 public static long getTotalTxBytes() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800791 try {
792 return getStatsService().getTotalStats(TYPE_TX_BYTES);
793 } catch (RemoteException e) {
794 throw e.rethrowFromSystemServer();
795 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700796 }
Ken Shirriffae521152009-12-07 15:56:05 -0800797
798 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700799 * Return number of bytes received since device boot. Counts packets across
800 * all network interfaces, and always increases monotonically since device
801 * boot. Statistics are measured at the network layer, so they include both
802 * TCP and UDP usage.
803 * <p>
804 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
805 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800806 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700807 public static long getTotalRxBytes() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800808 try {
809 return getStatsService().getTotalStats(TYPE_RX_BYTES);
810 } catch (RemoteException e) {
811 throw e.rethrowFromSystemServer();
812 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700813 }
Ken Shirriffae521152009-12-07 15:56:05 -0800814
815 /**
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800816 * Return number of bytes transmitted by the given UID since device boot.
817 * Counts packets across all network interfaces, and always increases
818 * monotonically since device boot. Statistics are measured at the network
819 * layer, so they include both TCP and UDP usage.
820 * <p>
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700821 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
822 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
823 * <p>
824 * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
825 * report traffic statistics for the calling UID. It will return
826 * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
827 * historical network statistics belonging to other UIDs, use
828 * {@link NetworkStatsManager}.
Ken Shirriffae521152009-12-07 15:56:05 -0800829 *
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800830 * @see android.os.Process#myUid()
831 * @see android.content.pm.ApplicationInfo#uid
Ken Shirriffae521152009-12-07 15:56:05 -0800832 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800833 public static long getUidTxBytes(int uid) {
Chenbo Fengd80a6ed2019-06-17 16:22:28 -0700834 try {
835 return getStatsService().getUidStats(uid, TYPE_TX_BYTES);
836 } catch (RemoteException e) {
837 throw e.rethrowFromSystemServer();
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700838 }
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800839 }
Ken Shirriffae521152009-12-07 15:56:05 -0800840
841 /**
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800842 * Return number of bytes received by the given UID since device boot.
843 * Counts packets across all network interfaces, and always increases
844 * monotonically since device boot. Statistics are measured at the network
845 * layer, so they include both TCP and UDP usage.
846 * <p>
Dianne Hackborne9d72072013-02-25 15:55:37 -0800847 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800848 * {@link #UNSUPPORTED} on devices where statistics aren't available.
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700849 * <p>
850 * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
851 * report traffic statistics for the calling UID. It will return
852 * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
853 * historical network statistics belonging to other UIDs, use
854 * {@link NetworkStatsManager}.
Ken Shirriffae521152009-12-07 15:56:05 -0800855 *
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800856 * @see android.os.Process#myUid()
857 * @see android.content.pm.ApplicationInfo#uid
Ken Shirriffae521152009-12-07 15:56:05 -0800858 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800859 public static long getUidRxBytes(int uid) {
Chenbo Fengd80a6ed2019-06-17 16:22:28 -0700860 try {
861 return getStatsService().getUidStats(uid, TYPE_RX_BYTES);
862 } catch (RemoteException e) {
863 throw e.rethrowFromSystemServer();
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700864 }
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800865 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800866
867 /**
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800868 * Return number of packets transmitted by the given UID since device boot.
869 * Counts packets across all network interfaces, and always increases
870 * monotonically since device boot. Statistics are measured at the network
871 * layer, so they include both TCP and UDP usage.
872 * <p>
Dianne Hackborne9d72072013-02-25 15:55:37 -0800873 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800874 * {@link #UNSUPPORTED} on devices where statistics aren't available.
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700875 * <p>
876 * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
877 * report traffic statistics for the calling UID. It will return
878 * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
879 * historical network statistics belonging to other UIDs, use
880 * {@link NetworkStatsManager}.
Ashish Sharmadf852d82011-01-27 15:52:38 -0800881 *
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800882 * @see android.os.Process#myUid()
883 * @see android.content.pm.ApplicationInfo#uid
Ashish Sharmadf852d82011-01-27 15:52:38 -0800884 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800885 public static long getUidTxPackets(int uid) {
Chenbo Fengd80a6ed2019-06-17 16:22:28 -0700886 try {
887 return getStatsService().getUidStats(uid, TYPE_TX_PACKETS);
888 } catch (RemoteException e) {
889 throw e.rethrowFromSystemServer();
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700890 }
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800891 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800892
893 /**
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800894 * Return number of packets received by the given UID since device boot.
895 * Counts packets across all network interfaces, and always increases
896 * monotonically since device boot. Statistics are measured at the network
897 * layer, so they include both TCP and UDP usage.
898 * <p>
Dianne Hackborne9d72072013-02-25 15:55:37 -0800899 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800900 * {@link #UNSUPPORTED} on devices where statistics aren't available.
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700901 * <p>
902 * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
903 * report traffic statistics for the calling UID. It will return
904 * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
905 * historical network statistics belonging to other UIDs, use
906 * {@link NetworkStatsManager}.
Ashish Sharmadf852d82011-01-27 15:52:38 -0800907 *
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800908 * @see android.os.Process#myUid()
909 * @see android.content.pm.ApplicationInfo#uid
Ashish Sharmadf852d82011-01-27 15:52:38 -0800910 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800911 public static long getUidRxPackets(int uid) {
Chenbo Fengd80a6ed2019-06-17 16:22:28 -0700912 try {
913 return getStatsService().getUidStats(uid, TYPE_RX_PACKETS);
914 } catch (RemoteException e) {
915 throw e.rethrowFromSystemServer();
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700916 }
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800917 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800918
919 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -0800920 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800921 * transport layer statistics are no longer available, and will
922 * always return {@link #UNSUPPORTED}.
923 * @see #getUidTxBytes(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -0800924 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800925 @Deprecated
926 public static long getUidTcpTxBytes(int uid) {
927 return UNSUPPORTED;
928 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800929
930 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -0800931 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800932 * transport layer statistics are no longer available, and will
933 * always return {@link #UNSUPPORTED}.
934 * @see #getUidRxBytes(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -0800935 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800936 @Deprecated
937 public static long getUidTcpRxBytes(int uid) {
938 return UNSUPPORTED;
939 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800940
941 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -0800942 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800943 * transport layer statistics are no longer available, and will
944 * always return {@link #UNSUPPORTED}.
945 * @see #getUidTxBytes(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -0800946 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800947 @Deprecated
948 public static long getUidUdpTxBytes(int uid) {
949 return UNSUPPORTED;
950 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800951
952 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -0800953 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800954 * transport layer statistics are no longer available, and will
955 * always return {@link #UNSUPPORTED}.
956 * @see #getUidRxBytes(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -0800957 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800958 @Deprecated
959 public static long getUidUdpRxBytes(int uid) {
960 return UNSUPPORTED;
961 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800962
963 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -0800964 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800965 * transport layer statistics are no longer available, and will
966 * always return {@link #UNSUPPORTED}.
967 * @see #getUidTxPackets(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -0800968 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800969 @Deprecated
970 public static long getUidTcpTxSegments(int uid) {
971 return UNSUPPORTED;
972 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800973
974 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -0800975 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800976 * transport layer statistics are no longer available, and will
977 * always return {@link #UNSUPPORTED}.
978 * @see #getUidRxPackets(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -0800979 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800980 @Deprecated
981 public static long getUidTcpRxSegments(int uid) {
982 return UNSUPPORTED;
983 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800984
Ashish Sharmadf852d82011-01-27 15:52:38 -0800985 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -0800986 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800987 * transport layer statistics are no longer available, and will
988 * always return {@link #UNSUPPORTED}.
989 * @see #getUidTxPackets(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -0800990 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800991 @Deprecated
992 public static long getUidUdpTxPackets(int uid) {
993 return UNSUPPORTED;
994 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800995
996 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -0800997 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800998 * transport layer statistics are no longer available, and will
999 * always return {@link #UNSUPPORTED}.
1000 * @see #getUidRxPackets(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -08001001 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001002 @Deprecated
1003 public static long getUidUdpRxPackets(int uid) {
1004 return UNSUPPORTED;
1005 }
Jeff Sharkey33936ac2011-05-17 14:55:15 -07001006
1007 /**
1008 * Return detailed {@link NetworkStats} for the current UID. Requires no
1009 * special permission.
1010 */
Jeff Sharkey7407e092011-07-19 23:47:12 -07001011 private static NetworkStats getDataLayerSnapshotForUid(Context context) {
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -07001012 // TODO: take snapshot locally, since proc file is now visible
Jeff Sharkey33936ac2011-05-17 14:55:15 -07001013 final int uid = android.os.Process.myUid();
1014 try {
Jeff Sharkey8308b9b2012-04-10 19:48:07 -07001015 return getStatsService().getDataLayerSnapshotForUid(uid);
Jeff Sharkey33936ac2011-05-17 14:55:15 -07001016 } catch (RemoteException e) {
Jeff Sharkeybc08d072016-02-26 13:03:01 -07001017 throw e.rethrowFromSystemServer();
Jeff Sharkey33936ac2011-05-17 14:55:15 -07001018 }
1019 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -07001020
1021 /**
1022 * Return set of any ifaces associated with mobile networks since boot.
1023 * Interfaces are never removed from this list, so counters should always be
1024 * monotonic.
1025 */
Chalard Jean3cfb4992019-04-09 15:46:21 +09001026 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey8308b9b2012-04-10 19:48:07 -07001027 private static String[] getMobileIfaces() {
1028 try {
1029 return getStatsService().getMobileIfaces();
1030 } catch (RemoteException e) {
Jeff Sharkeybc08d072016-02-26 13:03:01 -07001031 throw e.rethrowFromSystemServer();
Jeff Sharkey8308b9b2012-04-10 19:48:07 -07001032 }
1033 }
1034
junyulaiea236322020-10-06 11:59:56 +08001035 // NOTE: keep these in sync with {@code com_android_server_net_NetworkStatsService.cpp}.
1036 /** {@hide} */
1037 public static final int TYPE_RX_BYTES = 0;
1038 /** {@hide} */
1039 public static final int TYPE_RX_PACKETS = 1;
1040 /** {@hide} */
1041 public static final int TYPE_TX_BYTES = 2;
1042 /** {@hide} */
1043 public static final int TYPE_TX_PACKETS = 3;
1044 /** {@hide} */
1045 public static final int TYPE_TCP_RX_PACKETS = 4;
1046 /** {@hide} */
1047 public static final int TYPE_TCP_TX_PACKETS = 5;
Ken Shirriffae521152009-12-07 15:56:05 -08001048}