blob: a69b38d0d96d21401bd13e521362b39aa5ad1d3d [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;
Lorenzo Colittid2ae7392022-01-29 21:07:33 +090034import android.os.StrictMode;
Junyu Lai3355c402022-01-25 07:40:06 +000035import android.util.Log;
Jeff Sharkey33936ac2011-05-17 14:55:15 -070036
Jeff Sharkey1fb74312017-11-29 11:18:23 -070037import java.io.FileDescriptor;
38import java.io.IOException;
Jeff Sharkey7b124cb2015-12-04 15:21:52 -070039import java.net.DatagramSocket;
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -070040import java.net.Socket;
41import java.net.SocketException;
Ken Shirriffae521152009-12-07 15:56:05 -080042
43/**
Jeff Sharkey27c8a072016-03-09 16:40:15 -070044 * Class that provides network traffic statistics. These statistics include
Dan Egnoreaeb7022010-04-07 17:30:50 -070045 * bytes transmitted and received and network packets transmitted and received,
46 * over all interfaces, over the mobile interface, and on a per-UID basis.
Ken Shirriffae521152009-12-07 15:56:05 -080047 * <p>
Jeff Sharkey27c8a072016-03-09 16:40:15 -070048 * These statistics may not be available on all platforms. If the statistics are
49 * not supported by this device, {@link #UNSUPPORTED} will be returned.
50 * <p>
51 * Note that the statistics returned by this class reset and start from zero
52 * after every reboot. To access more robust historical network statistics data,
53 * use {@link NetworkStatsManager} instead.
Ken Shirriffae521152009-12-07 15:56:05 -080054 */
55public class TrafficStats {
Lorenzo Colittid2ae7392022-01-29 21:07:33 +090056 static {
57 System.loadLibrary("framework-connectivity-tiramisu-jni");
58 }
59
Junyu Lai3f7bb332021-12-28 16:18:43 +000060 private static final String TAG = TrafficStats.class.getSimpleName();
Ken Shirriffae521152009-12-07 15:56:05 -080061 /**
62 * The return value to indicate that the device does not support the statistic.
63 */
64 public final static int UNSUPPORTED = -1;
65
Junyu Lai1d3ce852021-12-27 13:56:59 +000066 /** @hide @deprecated use {@code DataUnit} instead to clarify SI-vs-IEC */
Jeff Sharkeya6886af2018-01-07 16:47:31 -070067 @Deprecated
Jeff Sharkey94a315c2012-02-03 14:50:07 -080068 public static final long KB_IN_BYTES = 1024;
Junyu Lai1d3ce852021-12-27 13:56:59 +000069 /** @hide @deprecated use {@code DataUnit} instead to clarify SI-vs-IEC */
Jeff Sharkeya6886af2018-01-07 16:47:31 -070070 @Deprecated
Jeff Sharkey94a315c2012-02-03 14:50:07 -080071 public static final long MB_IN_BYTES = KB_IN_BYTES * 1024;
Junyu Lai1d3ce852021-12-27 13:56:59 +000072 /** @hide @deprecated use {@code DataUnit} instead to clarify SI-vs-IEC */
Jeff Sharkeya6886af2018-01-07 16:47:31 -070073 @Deprecated
Jeff Sharkey94a315c2012-02-03 14:50:07 -080074 public static final long GB_IN_BYTES = MB_IN_BYTES * 1024;
Junyu Lai1d3ce852021-12-27 13:56:59 +000075 /** @hide @deprecated use {@code DataUnit} instead to clarify SI-vs-IEC */
Jeff Sharkeya6886af2018-01-07 16:47:31 -070076 @Deprecated
Jeff Sharkey6f2ba5e2015-03-18 11:27:19 -070077 public static final long TB_IN_BYTES = GB_IN_BYTES * 1024;
Junyu Lai1d3ce852021-12-27 13:56:59 +000078 /** @hide @deprecated use {@code DataUnit} instead to clarify SI-vs-IEC */
Jeff Sharkeya6886af2018-01-07 16:47:31 -070079 @Deprecated
Jeff Sharkey88069072015-06-15 21:09:10 -070080 public static final long PB_IN_BYTES = TB_IN_BYTES * 1024;
Jeff Sharkey94a315c2012-02-03 14:50:07 -080081
Jeff Sharkey1a3eb882011-05-28 20:56:34 -070082 /**
Jeff Sharkeyc04cda62011-06-19 01:08:12 -070083 * Special UID value used when collecting {@link NetworkStatsHistory} for
84 * removed applications.
85 *
86 * @hide
87 */
88 public static final int UID_REMOVED = -4;
89
90 /**
Jeff Sharkey987f5ff2011-09-16 01:52:49 -070091 * Special UID value used when collecting {@link NetworkStatsHistory} for
92 * tethering traffic.
93 *
94 * @hide
95 */
junyulai55041a42019-11-15 17:15:01 +080096 public static final int UID_TETHERING = NetworkStats.UID_TETHERING;
Jeff Sharkey987f5ff2011-09-16 01:52:49 -070097
98 /**
Chalard Jean8a93ab82019-04-09 11:16:56 +090099 * Tag values in this range are reserved for the network stack. The network stack is
100 * running as UID {@link android.os.Process.NETWORK_STACK_UID} when in the mainline
101 * module separate process, and as the system UID otherwise.
102 */
103 /** @hide */
104 @SystemApi
105 public static final int TAG_NETWORK_STACK_RANGE_START = 0xFFFFFD00;
106 /** @hide */
107 @SystemApi
108 public static final int TAG_NETWORK_STACK_RANGE_END = 0xFFFFFEFF;
109
110 /**
111 * Tags between 0xFFFFFF00 and 0xFFFFFFFF are reserved and used internally by system services
112 * like DownloadManager when performing traffic on behalf of an application.
113 */
114 // Please note there is no enforcement of these constants, so do not rely on them to
115 // determine that the caller is a system caller.
116 /** @hide */
117 @SystemApi
118 public static final int TAG_SYSTEM_IMPERSONATION_RANGE_START = 0xFFFFFF00;
119 /** @hide */
120 @SystemApi
121 public static final int TAG_SYSTEM_IMPERSONATION_RANGE_END = 0xFFFFFF0F;
122
123 /**
124 * Tag values between these ranges are reserved for the network stack to do traffic
125 * on behalf of applications. It is a subrange of the range above.
126 */
127 /** @hide */
128 @SystemApi
129 public static final int TAG_NETWORK_STACK_IMPERSONATION_RANGE_START = 0xFFFFFF80;
130 /** @hide */
131 @SystemApi
132 public static final int TAG_NETWORK_STACK_IMPERSONATION_RANGE_END = 0xFFFFFF8F;
133
134 /**
Jeff Sharkey92790062011-06-24 17:05:24 -0700135 * Default tag value for {@link DownloadManager} traffic.
136 *
137 * @hide
138 */
Jeff Sharkey987f5ff2011-09-16 01:52:49 -0700139 public static final int TAG_SYSTEM_DOWNLOAD = 0xFFFFFF01;
Jeff Sharkey92790062011-06-24 17:05:24 -0700140
141 /**
142 * Default tag value for {@link MediaPlayer} traffic.
143 *
144 * @hide
145 */
Jeff Sharkey987f5ff2011-09-16 01:52:49 -0700146 public static final int TAG_SYSTEM_MEDIA = 0xFFFFFF02;
Jeff Sharkey92790062011-06-24 17:05:24 -0700147
148 /**
Christopher Tatec1c71fd2015-11-10 10:49:20 -0800149 * Default tag value for {@link BackupManager} backup traffic; that is,
150 * traffic from the device to the storage backend.
Jeff Sharkey92790062011-06-24 17:05:24 -0700151 *
152 * @hide
153 */
Jeff Sharkey987f5ff2011-09-16 01:52:49 -0700154 public static final int TAG_SYSTEM_BACKUP = 0xFFFFFF03;
Jeff Sharkey92790062011-06-24 17:05:24 -0700155
Christopher Tatec1c71fd2015-11-10 10:49:20 -0800156 /**
157 * Default tag value for {@link BackupManager} restore traffic; that is,
158 * app data retrieved from the storage backend at install time.
159 *
160 * @hide
161 */
162 public static final int TAG_SYSTEM_RESTORE = 0xFFFFFF04;
163
Jeff Sharkey66dca172016-11-21 12:14:50 -0700164 /**
Jeff Sharkeyb1f97ac2017-08-11 15:04:12 -0600165 * Default tag value for code (typically APKs) downloaded by an app store on
166 * behalf of the app, such as updates.
Jeff Sharkey66dca172016-11-21 12:14:50 -0700167 *
168 * @hide
169 */
Jeff Sharkeyb1f97ac2017-08-11 15:04:12 -0600170 public static final int TAG_SYSTEM_APP = 0xFFFFFF05;
Jeff Sharkey8af5ad12017-06-26 19:50:41 -0600171
Chalard Jean8a93ab82019-04-09 11:16:56 +0900172 // TODO : remove this constant when Wifi code is updated
Jeff Sharkey8af5ad12017-06-26 19:50:41 -0600173 /** @hide */
Jeff Sharkey8af5ad12017-06-26 19:50:41 -0600174 public static final int TAG_SYSTEM_PROBE = 0xFFFFFF42;
Jeff Sharkey66dca172016-11-21 12:14:50 -0700175
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700176 private static INetworkStatsService sStatsService;
177
Chalard Jean3cfb4992019-04-09 15:46:21 +0900178 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700179 private synchronized static INetworkStatsService getStatsService() {
180 if (sStatsService == null) {
Junyu Lai92d5b4c2022-01-19 08:33:21 +0000181 throw new IllegalStateException("TrafficStats not initialized, uid="
182 + Binder.getCallingUid());
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700183 }
184 return sStatsService;
185 }
186
Jeff Sharkey92790062011-06-24 17:05:24 -0700187 /**
Jeff Sharkey33936ac2011-05-17 14:55:15 -0700188 * Snapshot of {@link NetworkStats} when the currently active profiling
189 * session started, or {@code null} if no session active.
190 *
191 * @see #startDataProfiling(Context)
192 * @see #stopDataProfiling(Context)
193 */
194 private static NetworkStats sActiveProfilingStart;
195
196 private static Object sProfilingLock = new Object();
197
Benedict Wong083faee2017-12-03 19:42:36 -0800198 private static final String LOOPBACK_IFACE = "lo";
199
Jeff Sharkey33936ac2011-05-17 14:55:15 -0700200 /**
Junyu Lai92d5b4c2022-01-19 08:33:21 +0000201 * Initialization {@link TrafficStats} with the context, to
202 * allow {@link TrafficStats} to fetch the needed binder.
203 *
204 * @param context a long-lived context, such as the application context or system
205 * server context.
206 * @hide
207 */
junyulai44e61e22022-03-01 16:53:28 +0800208 @SystemApi(client = MODULE_LIBRARIES)
Junyu Lai92d5b4c2022-01-19 08:33:21 +0000209 @SuppressLint("VisiblySynchronized")
210 public static synchronized void init(@NonNull final Context context) {
211 if (sStatsService != null) {
212 throw new IllegalStateException("TrafficStats is already initialized, uid="
213 + Binder.getCallingUid());
214 }
215 final NetworkStatsManager statsManager =
216 context.getSystemService(NetworkStatsManager.class);
Junyu Lai3355c402022-01-25 07:40:06 +0000217 if (statsManager == null) {
218 // TODO: Currently Process.isSupplemental is not working yet, because it depends on
219 // process to run in a certain UID range, which is not true for now. Change this
220 // to Log.wtf once Process.isSupplemental is ready.
221 Log.e(TAG, "TrafficStats not initialized, uid=" + Binder.getCallingUid());
222 return;
223 }
Junyu Lai92d5b4c2022-01-19 08:33:21 +0000224 sStatsService = statsManager.getBinder();
225 }
226
227 /**
Junyu Lai8e58c822022-01-17 17:05:30 +0000228 * Attach the socket tagger implementation to the current process, to
229 * get notified when a socket's {@link FileDescriptor} is assigned to
230 * a thread. See {@link SocketTagger#set(SocketTagger)}.
231 *
232 * @hide
233 */
234 @SystemApi(client = MODULE_LIBRARIES)
235 public static void attachSocketTagger() {
Lorenzo Colittid2ae7392022-01-29 21:07:33 +0900236 dalvik.system.SocketTagger.set(new SocketTagger());
Junyu Lai8e58c822022-01-17 17:05:30 +0000237 }
238
Lorenzo Colittid2ae7392022-01-29 21:07:33 +0900239 private static class SocketTagger extends dalvik.system.SocketTagger {
240
241 // TODO: set to false
242 private static final boolean LOGD = true;
243
244 SocketTagger() {
245 }
246
247 @Override
248 public void tag(FileDescriptor fd) throws SocketException {
249 final UidTag tagInfo = sThreadUidTag.get();
250 if (LOGD) {
251 Log.d(TAG, "tagSocket(" + fd.getInt$() + ") with statsTag=0x"
252 + Integer.toHexString(tagInfo.tag) + ", statsUid=" + tagInfo.uid);
253 }
254 if (tagInfo.tag == -1) {
255 StrictMode.noteUntaggedSocket();
256 }
257
258 if (tagInfo.tag == -1 && tagInfo.uid == -1) return;
259 final int errno = native_tagSocketFd(fd, tagInfo.tag, tagInfo.uid);
260 if (errno < 0) {
261 Log.i(TAG, "tagSocketFd(" + fd.getInt$() + ", "
262 + tagInfo.tag + ", "
263 + tagInfo.uid + ") failed with errno" + errno);
264 }
265 }
266
267 @Override
268 public void untag(FileDescriptor fd) throws SocketException {
269 if (LOGD) {
270 Log.i(TAG, "untagSocket(" + fd.getInt$() + ")");
271 }
272
273 final UidTag tagInfo = sThreadUidTag.get();
274 if (tagInfo.tag == -1 && tagInfo.uid == -1) return;
275
276 final int errno = native_untagSocketFd(fd);
277 if (errno < 0) {
278 Log.w(TAG, "untagSocket(" + fd.getInt$() + ") failed with errno " + errno);
279 }
280 }
281 }
282
283 private static native int native_tagSocketFd(FileDescriptor fd, int tag, int uid);
284 private static native int native_untagSocketFd(FileDescriptor fd);
285
286 private static class UidTag {
287 public int tag = -1;
288 public int uid = -1;
289 }
290
291 private static ThreadLocal<UidTag> sThreadUidTag = new ThreadLocal<UidTag>() {
292 @Override
293 protected UidTag initialValue() {
294 return new UidTag();
295 }
296 };
297
Junyu Lai8e58c822022-01-17 17:05:30 +0000298 /**
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700299 * Set active tag to use when accounting {@link Socket} traffic originating
300 * from the current thread. Only one active tag per thread is supported.
301 * <p>
302 * Changes only take effect during subsequent calls to
303 * {@link #tagSocket(Socket)}.
Jeff Sharkey987f5ff2011-09-16 01:52:49 -0700304 * <p>
305 * Tags between {@code 0xFFFFFF00} and {@code 0xFFFFFFFF} are reserved and
306 * used internally by system services like {@link DownloadManager} when
307 * performing traffic on behalf of an application.
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700308 *
309 * @see #clearThreadStatsTag()
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700310 */
Jeff Sharkey92790062011-06-24 17:05:24 -0700311 public static void setThreadStatsTag(int tag) {
Lorenzo Colittid2ae7392022-01-29 21:07:33 +0900312 getAndSetThreadStatsTag(tag);
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700313 }
314
Jeff Sharkey92790062011-06-24 17:05:24 -0700315 /**
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600316 * Set active tag to use when accounting {@link Socket} traffic originating
Jeff Sharkey289eac12017-01-19 11:55:54 -0700317 * from the current thread. Only one active tag per thread is supported.
318 * <p>
319 * Changes only take effect during subsequent calls to
320 * {@link #tagSocket(Socket)}.
321 * <p>
322 * Tags between {@code 0xFFFFFF00} and {@code 0xFFFFFFFF} are reserved and
323 * used internally by system services like {@link DownloadManager} when
324 * performing traffic on behalf of an application.
325 *
326 * @return the current tag for the calling thread, which can be used to
327 * restore any existing values after a nested operation is finished
328 */
329 public static int getAndSetThreadStatsTag(int tag) {
Lorenzo Colittid2ae7392022-01-29 21:07:33 +0900330 final int old = sThreadUidTag.get().tag;
331 sThreadUidTag.get().tag = tag;
332 return old;
Jeff Sharkey289eac12017-01-19 11:55:54 -0700333 }
334
335 /**
336 * Set active tag to use when accounting {@link Socket} traffic originating
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600337 * from the current thread. The tag used internally is well-defined to
338 * distinguish all backup-related traffic.
339 *
Christopher Tate5a1878d2014-08-06 14:19:56 -0700340 * @hide
341 */
342 @SystemApi
343 public static void setThreadStatsTagBackup() {
344 setThreadStatsTag(TAG_SYSTEM_BACKUP);
345 }
346
347 /**
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600348 * Set active tag to use when accounting {@link Socket} traffic originating
349 * from the current thread. The tag used internally is well-defined to
350 * distinguish all restore-related traffic.
351 *
Christopher Tatec1c71fd2015-11-10 10:49:20 -0800352 * @hide
353 */
354 @SystemApi
355 public static void setThreadStatsTagRestore() {
356 setThreadStatsTag(TAG_SYSTEM_RESTORE);
357 }
358
359 /**
Jeff Sharkey8af5ad12017-06-26 19:50:41 -0600360 * Set active tag to use when accounting {@link Socket} traffic originating
361 * from the current thread. The tag used internally is well-defined to
Jeff Sharkeyb1f97ac2017-08-11 15:04:12 -0600362 * distinguish all code (typically APKs) downloaded by an app store on
363 * behalf of the app, such as updates.
Jeff Sharkey8af5ad12017-06-26 19:50:41 -0600364 *
365 * @hide
366 */
367 @SystemApi
Jeff Sharkeyb1f97ac2017-08-11 15:04:12 -0600368 public static void setThreadStatsTagApp() {
369 setThreadStatsTag(TAG_SYSTEM_APP);
Jeff Sharkey8af5ad12017-06-26 19:50:41 -0600370 }
371
372 /**
Junyu Laiab2c35e2022-01-18 02:46:23 +0000373 * Set active tag to use when accounting {@link Socket} traffic originating
374 * from the current thread. The tag used internally is well-defined to
375 * distinguish all download provider traffic.
376 *
377 * @hide
378 */
junyulai44e61e22022-03-01 16:53:28 +0800379 @SystemApi(client = MODULE_LIBRARIES)
Junyu Laiab2c35e2022-01-18 02:46:23 +0000380 public static void setThreadStatsTagDownload() {
381 setThreadStatsTag(TAG_SYSTEM_DOWNLOAD);
382 }
383
384 /**
Alon Albert2c295f02011-07-19 11:16:09 +0300385 * Get the active tag used when accounting {@link Socket} traffic originating
386 * from the current thread. Only one active tag per thread is supported.
387 * {@link #tagSocket(Socket)}.
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700388 *
389 * @see #setThreadStatsTag(int)
Alon Albert2c295f02011-07-19 11:16:09 +0300390 */
391 public static int getThreadStatsTag() {
Lorenzo Colittid2ae7392022-01-29 21:07:33 +0900392 return sThreadUidTag.get().tag;
Alon Albert2c295f02011-07-19 11:16:09 +0300393 }
394
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700395 /**
396 * Clear any active tag set to account {@link Socket} traffic originating
397 * from the current thread.
398 *
399 * @see #setThreadStatsTag(int)
400 */
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700401 public static void clearThreadStatsTag() {
Lorenzo Colittid2ae7392022-01-29 21:07:33 +0900402 sThreadUidTag.get().tag = -1;
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700403 }
404
405 /**
406 * Set specific UID to use when accounting {@link Socket} traffic
407 * originating from the current thread. Designed for use when performing an
Jeff Sharkey17a38752018-03-26 13:11:33 -0600408 * operation on behalf of another application, or when another application
409 * is performing operations on your behalf.
410 * <p>
411 * Any app can <em>accept</em> blame for traffic performed on a socket
412 * originally created by another app by calling this method with the
413 * {@link android.system.Os#getuid()} value. However, only apps holding the
414 * {@code android.Manifest.permission#UPDATE_DEVICE_STATS} permission may
415 * <em>assign</em> blame to another UIDs.
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700416 * <p>
417 * Changes only take effect during subsequent calls to
418 * {@link #tagSocket(Socket)}.
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700419 */
Aurimas Liutikas9de1e0e2020-11-12 18:29:11 -0800420 @SuppressLint("RequiresPermission")
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700421 public static void setThreadStatsUid(int uid) {
Lorenzo Colittid2ae7392022-01-29 21:07:33 +0900422 sThreadUidTag.get().uid = uid;
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700423 }
424
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600425 /**
Jeff Sharkey17a38752018-03-26 13:11:33 -0600426 * Get the active UID used when accounting {@link Socket} traffic originating
427 * from the current thread. Only one active tag per thread is supported.
428 * {@link #tagSocket(Socket)}.
429 *
430 * @see #setThreadStatsUid(int)
431 */
432 public static int getThreadStatsUid() {
Lorenzo Colittid2ae7392022-01-29 21:07:33 +0900433 return sThreadUidTag.get().uid;
Jeff Sharkey17a38752018-03-26 13:11:33 -0600434 }
435
436 /**
Jeff Sharkey1fb74312017-11-29 11:18:23 -0700437 * Set specific UID to use when accounting {@link Socket} traffic
438 * originating from the current thread as the calling UID. Designed for use
439 * when another application is performing operations on your behalf.
440 * <p>
441 * Changes only take effect during subsequent calls to
442 * {@link #tagSocket(Socket)}.
Jeff Sharkey17a38752018-03-26 13:11:33 -0600443 *
444 * @removed
445 * @deprecated use {@link #setThreadStatsUid(int)} instead.
Jeff Sharkey1fb74312017-11-29 11:18:23 -0700446 */
Jeff Sharkey17a38752018-03-26 13:11:33 -0600447 @Deprecated
Jeff Sharkey1fb74312017-11-29 11:18:23 -0700448 public static void setThreadStatsUidSelf() {
449 setThreadStatsUid(android.os.Process.myUid());
450 }
451
452 /**
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600453 * Clear any active UID set to account {@link Socket} traffic originating
454 * from the current thread.
455 *
456 * @see #setThreadStatsUid(int)
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600457 */
Aurimas Liutikas9de1e0e2020-11-12 18:29:11 -0800458 @SuppressLint("RequiresPermission")
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700459 public static void clearThreadStatsUid() {
Lorenzo Colittid2ae7392022-01-29 21:07:33 +0900460 setThreadStatsUid(-1);
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700461 }
462
463 /**
464 * Tag the given {@link Socket} with any statistics parameters active for
465 * the current thread. Subsequent calls always replace any existing
466 * parameters. When finished, call {@link #untagSocket(Socket)} to remove
467 * statistics parameters.
468 *
Jeff Sharkey92790062011-06-24 17:05:24 -0700469 * @see #setThreadStatsTag(int)
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700470 */
junyulai44e61e22022-03-01 16:53:28 +0800471 public static void tagSocket(@NonNull Socket socket) throws SocketException {
Jesse Wilsonb05f41c2011-06-28 19:06:31 -0700472 SocketTagger.get().tag(socket);
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700473 }
474
475 /**
476 * Remove any statistics parameters from the given {@link Socket}.
koprivac134e242018-07-23 18:19:39 -0700477 * <p>
478 * In Android 8.1 (API level 27) and lower, a socket is automatically
479 * untagged when it's sent to another process using binder IPC with a
480 * {@code ParcelFileDescriptor} container. In Android 9.0 (API level 28)
481 * and higher, the socket tag is kept when the socket is sent to another
482 * process using binder IPC. You can mimic the previous behavior by
483 * calling {@code untagSocket()} before sending the socket to another
484 * process.
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700485 */
junyulai44e61e22022-03-01 16:53:28 +0800486 public static void untagSocket(@NonNull Socket socket) throws SocketException {
Jesse Wilsonb05f41c2011-06-28 19:06:31 -0700487 SocketTagger.get().untag(socket);
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700488 }
489
490 /**
Jeff Sharkey7b124cb2015-12-04 15:21:52 -0700491 * Tag the given {@link DatagramSocket} with any statistics parameters
492 * active for the current thread. Subsequent calls always replace any
493 * existing parameters. When finished, call
494 * {@link #untagDatagramSocket(DatagramSocket)} to remove statistics
495 * parameters.
496 *
497 * @see #setThreadStatsTag(int)
Jeff Sharkey7b124cb2015-12-04 15:21:52 -0700498 */
junyulai44e61e22022-03-01 16:53:28 +0800499 public static void tagDatagramSocket(@NonNull DatagramSocket socket) throws SocketException {
Jeff Sharkey7b124cb2015-12-04 15:21:52 -0700500 SocketTagger.get().tag(socket);
501 }
502
503 /**
504 * Remove any statistics parameters from the given {@link DatagramSocket}.
505 */
junyulai44e61e22022-03-01 16:53:28 +0800506 public static void untagDatagramSocket(@NonNull DatagramSocket socket) throws SocketException {
Jeff Sharkey7b124cb2015-12-04 15:21:52 -0700507 SocketTagger.get().untag(socket);
508 }
509
510 /**
Jeff Sharkey1fb74312017-11-29 11:18:23 -0700511 * Tag the given {@link FileDescriptor} socket with any statistics
512 * parameters active for the current thread. Subsequent calls always replace
513 * any existing parameters. When finished, call
514 * {@link #untagFileDescriptor(FileDescriptor)} to remove statistics
515 * parameters.
516 *
517 * @see #setThreadStatsTag(int)
518 */
junyulai44e61e22022-03-01 16:53:28 +0800519 public static void tagFileDescriptor(@NonNull FileDescriptor fd) throws IOException {
Jeff Sharkey1fb74312017-11-29 11:18:23 -0700520 SocketTagger.get().tag(fd);
521 }
522
523 /**
524 * Remove any statistics parameters from the given {@link FileDescriptor}
525 * socket.
526 */
junyulai44e61e22022-03-01 16:53:28 +0800527 public static void untagFileDescriptor(@NonNull FileDescriptor fd) throws IOException {
Jeff Sharkey1fb74312017-11-29 11:18:23 -0700528 SocketTagger.get().untag(fd);
529 }
530
531 /**
Jeff Sharkey33936ac2011-05-17 14:55:15 -0700532 * Start profiling data usage for current UID. Only one profiling session
533 * can be active at a time.
534 *
535 * @hide
536 */
537 public static void startDataProfiling(Context context) {
538 synchronized (sProfilingLock) {
539 if (sActiveProfilingStart != null) {
540 throw new IllegalStateException("already profiling data");
541 }
542
543 // take snapshot in time; we calculate delta later
Jeff Sharkey7407e092011-07-19 23:47:12 -0700544 sActiveProfilingStart = getDataLayerSnapshotForUid(context);
Jeff Sharkey33936ac2011-05-17 14:55:15 -0700545 }
546 }
547
548 /**
549 * Stop profiling data usage for current UID.
550 *
551 * @return Detailed {@link NetworkStats} of data that occurred since last
552 * {@link #startDataProfiling(Context)} call.
553 * @hide
554 */
555 public static NetworkStats stopDataProfiling(Context context) {
556 synchronized (sProfilingLock) {
557 if (sActiveProfilingStart == null) {
558 throw new IllegalStateException("not profiling data");
559 }
560
Jeff Sharkeyef7bded2012-01-10 17:24:44 -0800561 // subtract starting values and return delta
562 final NetworkStats profilingStop = getDataLayerSnapshotForUid(context);
563 final NetworkStats profilingDelta = NetworkStats.subtract(
Jeff Sharkeybfe82682012-01-11 18:38:16 -0800564 profilingStop, sActiveProfilingStart, null, null);
Jeff Sharkeyef7bded2012-01-10 17:24:44 -0800565 sActiveProfilingStart = null;
566 return profilingDelta;
Jeff Sharkey33936ac2011-05-17 14:55:15 -0700567 }
568 }
569
570 /**
Jeff Sharkey60ca0232011-08-24 15:42:09 -0700571 * Increment count of network operations performed under the accounting tag
572 * currently active on the calling thread. This can be used to derive
573 * bytes-per-operation.
574 *
575 * @param operationCount Number of operations to increment count by.
576 */
577 public static void incrementOperationCount(int operationCount) {
578 final int tag = getThreadStatsTag();
579 incrementOperationCount(tag, operationCount);
580 }
581
582 /**
Jeff Sharkey7407e092011-07-19 23:47:12 -0700583 * Increment count of network operations performed under the given
584 * accounting tag. This can be used to derive bytes-per-operation.
585 *
586 * @param tag Accounting tag used in {@link #setThreadStatsTag(int)}.
587 * @param operationCount Number of operations to increment count by.
588 */
589 public static void incrementOperationCount(int tag, int operationCount) {
Jeff Sharkey7407e092011-07-19 23:47:12 -0700590 final int uid = android.os.Process.myUid();
591 try {
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700592 getStatsService().incrementOperationCount(uid, tag, operationCount);
Jeff Sharkey7407e092011-07-19 23:47:12 -0700593 } catch (RemoteException e) {
Jeff Sharkeybc08d072016-02-26 13:03:01 -0700594 throw e.rethrowFromSystemServer();
Jeff Sharkey7407e092011-07-19 23:47:12 -0700595 }
596 }
597
Jeff Sharkey920d9042012-04-06 11:12:08 -0700598 /** {@hide} */
599 public static void closeQuietly(INetworkStatsSession session) {
600 // TODO: move to NetworkStatsService once it exists
601 if (session != null) {
602 try {
603 session.close();
604 } catch (RuntimeException rethrown) {
605 throw rethrown;
606 } catch (Exception ignored) {
607 }
608 }
609 }
610
Chenbo Feng905f0342018-01-25 11:43:52 -0800611 private static long addIfSupported(long stat) {
612 return (stat == UNSUPPORTED) ? 0 : stat;
613 }
614
Jeff Sharkey7407e092011-07-19 23:47:12 -0700615 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700616 * Return number of packets transmitted across mobile networks since device
617 * boot. Counts packets across all mobile network interfaces, and always
618 * increases monotonically since device boot. Statistics are measured at the
619 * network layer, so they include both TCP and UDP usage.
620 * <p>
621 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
622 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800623 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700624 public static long getMobileTxPackets() {
625 long total = 0;
626 for (String iface : getMobileIfaces()) {
Chenbo Feng905f0342018-01-25 11:43:52 -0800627 total += addIfSupported(getTxPackets(iface));
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700628 }
629 return total;
630 }
Ken Shirriffae521152009-12-07 15:56:05 -0800631
632 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700633 * Return number of packets received across mobile networks since device
634 * boot. Counts packets across all mobile network interfaces, and always
635 * increases monotonically since device boot. Statistics are measured at the
636 * network layer, so they include both TCP and UDP usage.
637 * <p>
638 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
639 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800640 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700641 public static long getMobileRxPackets() {
642 long total = 0;
643 for (String iface : getMobileIfaces()) {
Chenbo Feng905f0342018-01-25 11:43:52 -0800644 total += addIfSupported(getRxPackets(iface));
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700645 }
646 return total;
647 }
Ken Shirriffae521152009-12-07 15:56:05 -0800648
649 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700650 * Return number of bytes transmitted across mobile networks since device
651 * boot. Counts packets across all mobile network interfaces, and always
652 * increases monotonically since device boot. Statistics are measured at the
653 * network layer, so they include both TCP and UDP usage.
654 * <p>
655 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
656 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800657 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700658 public static long getMobileTxBytes() {
659 long total = 0;
660 for (String iface : getMobileIfaces()) {
Chenbo Feng905f0342018-01-25 11:43:52 -0800661 total += addIfSupported(getTxBytes(iface));
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700662 }
663 return total;
664 }
Ken Shirriffae521152009-12-07 15:56:05 -0800665
666 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700667 * Return number of bytes received across mobile networks since device boot.
668 * Counts packets across all mobile network interfaces, and always increases
669 * monotonically since device boot. Statistics are measured at the network
670 * layer, so they include both TCP and UDP usage.
671 * <p>
672 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
673 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800674 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700675 public static long getMobileRxBytes() {
676 long total = 0;
677 for (String iface : getMobileIfaces()) {
Chenbo Feng905f0342018-01-25 11:43:52 -0800678 total += addIfSupported(getRxBytes(iface));
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700679 }
680 return total;
681 }
Ken Shirriffae521152009-12-07 15:56:05 -0800682
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800683 /** {@hide} */
Mathew Inwoodfe2fed72020-11-04 09:29:36 +0000684 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800685 public static long getMobileTcpRxPackets() {
Maciej Żenczykowski66645a82023-08-12 08:26:44 +0000686 return UNSUPPORTED;
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800687 }
688
689 /** {@hide} */
Mathew Inwoodfe2fed72020-11-04 09:29:36 +0000690 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800691 public static long getMobileTcpTxPackets() {
Maciej Żenczykowski66645a82023-08-12 08:26:44 +0000692 return UNSUPPORTED;
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800693 }
694
Aaron Huang443651d2019-09-27 22:31:22 +0800695 /**
junyulai3154d512020-09-29 14:19:24 +0800696 * Return the number of packets transmitted on the specified interface since the interface
697 * was created. Statistics are measured at the network layer, so both TCP and
Aaron Huang443651d2019-09-27 22:31:22 +0800698 * UDP usage are included.
699 *
junyulai3154d512020-09-29 14:19:24 +0800700 * Note that the returned values are partial statistics that do not count data from several
701 * sources and do not apply several adjustments that are necessary for correctness, such
702 * as adjusting for VPN apps, IPv6-in-IPv4 translation, etc. These values can be used to
703 * determine whether traffic is being transferred on the specific interface but are not a
704 * substitute for the more accurate statistics provided by the {@link NetworkStatsManager}
705 * APIs.
706 *
Aaron Huang443651d2019-09-27 22:31:22 +0800707 * @param iface The name of the interface.
708 * @return The number of transmitted packets.
709 */
710 public static long getTxPackets(@NonNull String iface) {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800711 try {
712 return getStatsService().getIfaceStats(iface, TYPE_TX_PACKETS);
713 } catch (RemoteException e) {
714 throw e.rethrowFromSystemServer();
715 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700716 }
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800717
Aaron Huang443651d2019-09-27 22:31:22 +0800718 /**
junyulai3154d512020-09-29 14:19:24 +0800719 * Return the number of packets received on the specified interface since the interface was
720 * created. Statistics are measured at the network layer, so both TCP
Aaron Huang443651d2019-09-27 22:31:22 +0800721 * and UDP usage are included.
722 *
junyulai3154d512020-09-29 14:19:24 +0800723 * Note that the returned values are partial statistics that do not count data from several
724 * sources and do not apply several adjustments that are necessary for correctness, such
725 * as adjusting for VPN apps, IPv6-in-IPv4 translation, etc. These values can be used to
726 * determine whether traffic is being transferred on the specific interface but are not a
727 * substitute for the more accurate statistics provided by the {@link NetworkStatsManager}
728 * APIs.
729 *
Aaron Huang443651d2019-09-27 22:31:22 +0800730 * @param iface The name of the interface.
731 * @return The number of received packets.
732 */
733 public static long getRxPackets(@NonNull String iface) {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800734 try {
735 return getStatsService().getIfaceStats(iface, TYPE_RX_PACKETS);
736 } catch (RemoteException e) {
737 throw e.rethrowFromSystemServer();
738 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700739 }
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800740
junyulai3154d512020-09-29 14:19:24 +0800741 /**
742 * Return the number of bytes transmitted on the specified interface since the interface
743 * was created. Statistics are measured at the network layer, so both TCP and
744 * UDP usage are included.
745 *
746 * Note that the returned values are partial statistics that do not count data from several
747 * sources and do not apply several adjustments that are necessary for correctness, such
748 * as adjusting for VPN apps, IPv6-in-IPv4 translation, etc. These values can be used to
749 * determine whether traffic is being transferred on the specific interface but are not a
750 * substitute for the more accurate statistics provided by the {@link NetworkStatsManager}
751 * APIs.
752 *
753 * @param iface The name of the interface.
754 * @return The number of transmitted bytes.
755 */
756 public static long getTxBytes(@NonNull String iface) {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800757 try {
758 return getStatsService().getIfaceStats(iface, TYPE_TX_BYTES);
759 } catch (RemoteException e) {
760 throw e.rethrowFromSystemServer();
761 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700762 }
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800763
junyulai3154d512020-09-29 14:19:24 +0800764 /**
765 * Return the number of bytes received on the specified interface since the interface
766 * was created. Statistics are measured at the network layer, so both TCP
767 * and UDP usage are included.
768 *
769 * Note that the returned values are partial statistics that do not count data from several
770 * sources and do not apply several adjustments that are necessary for correctness, such
771 * as adjusting for VPN apps, IPv6-in-IPv4 translation, etc. These values can be used to
772 * determine whether traffic is being transferred on the specific interface but are not a
773 * substitute for the more accurate statistics provided by the {@link NetworkStatsManager}
774 * APIs.
775 *
776 * @param iface The name of the interface.
777 * @return The number of received bytes.
778 */
779 public static long getRxBytes(@NonNull String iface) {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800780 try {
781 return getStatsService().getIfaceStats(iface, TYPE_RX_BYTES);
782 } catch (RemoteException e) {
783 throw e.rethrowFromSystemServer();
784 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700785 }
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800786
Benedict Wong083faee2017-12-03 19:42:36 -0800787 /** {@hide} */
788 @TestApi
789 public static long getLoopbackTxPackets() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800790 try {
791 return getStatsService().getIfaceStats(LOOPBACK_IFACE, TYPE_TX_PACKETS);
792 } catch (RemoteException e) {
793 throw e.rethrowFromSystemServer();
794 }
Benedict Wong083faee2017-12-03 19:42:36 -0800795 }
796
797 /** {@hide} */
798 @TestApi
799 public static long getLoopbackRxPackets() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800800 try {
801 return getStatsService().getIfaceStats(LOOPBACK_IFACE, TYPE_RX_PACKETS);
802 } catch (RemoteException e) {
803 throw e.rethrowFromSystemServer();
804 }
Benedict Wong083faee2017-12-03 19:42:36 -0800805 }
806
807 /** {@hide} */
808 @TestApi
809 public static long getLoopbackTxBytes() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800810 try {
811 return getStatsService().getIfaceStats(LOOPBACK_IFACE, TYPE_TX_BYTES);
812 } catch (RemoteException e) {
813 throw e.rethrowFromSystemServer();
814 }
Benedict Wong083faee2017-12-03 19:42:36 -0800815 }
816
817 /** {@hide} */
818 @TestApi
819 public static long getLoopbackRxBytes() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800820 try {
821 return getStatsService().getIfaceStats(LOOPBACK_IFACE, TYPE_RX_BYTES);
822 } catch (RemoteException e) {
823 throw e.rethrowFromSystemServer();
824 }
Benedict Wong083faee2017-12-03 19:42:36 -0800825 }
826
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800827 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700828 * Return number of packets transmitted since device boot. Counts packets
829 * across all network interfaces, and always increases monotonically since
830 * device boot. Statistics are measured at the network layer, so they
831 * include both TCP and UDP usage.
832 * <p>
833 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
834 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800835 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700836 public static long getTotalTxPackets() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800837 try {
838 return getStatsService().getTotalStats(TYPE_TX_PACKETS);
839 } catch (RemoteException e) {
840 throw e.rethrowFromSystemServer();
841 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700842 }
Ken Shirriffae521152009-12-07 15:56:05 -0800843
844 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700845 * Return number of packets received since device boot. Counts packets
846 * across all network interfaces, and always increases monotonically since
847 * device boot. Statistics are measured at the network layer, so they
848 * include both TCP and UDP usage.
849 * <p>
850 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
851 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800852 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700853 public static long getTotalRxPackets() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800854 try {
855 return getStatsService().getTotalStats(TYPE_RX_PACKETS);
856 } catch (RemoteException e) {
857 throw e.rethrowFromSystemServer();
858 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700859 }
Ken Shirriffae521152009-12-07 15:56:05 -0800860
861 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700862 * Return number of bytes transmitted since device boot. Counts packets
863 * across all network interfaces, and always increases monotonically since
864 * device boot. Statistics are measured at the network layer, so they
865 * include both TCP and UDP usage.
866 * <p>
867 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
868 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800869 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700870 public static long getTotalTxBytes() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800871 try {
872 return getStatsService().getTotalStats(TYPE_TX_BYTES);
873 } catch (RemoteException e) {
874 throw e.rethrowFromSystemServer();
875 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700876 }
Ken Shirriffae521152009-12-07 15:56:05 -0800877
878 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700879 * Return number of bytes received since device boot. Counts packets across
880 * all network interfaces, and always increases monotonically since device
881 * boot. Statistics are measured at the network layer, so they include both
882 * TCP and UDP usage.
883 * <p>
884 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
885 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800886 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700887 public static long getTotalRxBytes() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800888 try {
889 return getStatsService().getTotalStats(TYPE_RX_BYTES);
890 } catch (RemoteException e) {
891 throw e.rethrowFromSystemServer();
892 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700893 }
Ken Shirriffae521152009-12-07 15:56:05 -0800894
895 /**
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800896 * Return number of bytes transmitted by the given UID since device boot.
897 * Counts packets across all network interfaces, and always increases
898 * monotonically since device boot. Statistics are measured at the network
899 * layer, so they include both TCP and UDP usage.
900 * <p>
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700901 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
902 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
903 * <p>
904 * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
905 * report traffic statistics for the calling UID. It will return
906 * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
907 * historical network statistics belonging to other UIDs, use
908 * {@link NetworkStatsManager}.
Ken Shirriffae521152009-12-07 15:56:05 -0800909 *
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800910 * @see android.os.Process#myUid()
911 * @see android.content.pm.ApplicationInfo#uid
Ken Shirriffae521152009-12-07 15:56:05 -0800912 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800913 public static long getUidTxBytes(int uid) {
Chenbo Fengd80a6ed2019-06-17 16:22:28 -0700914 try {
915 return getStatsService().getUidStats(uid, TYPE_TX_BYTES);
916 } catch (RemoteException e) {
917 throw e.rethrowFromSystemServer();
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700918 }
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800919 }
Ken Shirriffae521152009-12-07 15:56:05 -0800920
921 /**
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800922 * Return number of bytes received by the given UID since device boot.
923 * Counts packets across all network interfaces, and always increases
924 * monotonically since device boot. Statistics are measured at the network
925 * layer, so they include both TCP and UDP usage.
926 * <p>
Dianne Hackborne9d72072013-02-25 15:55:37 -0800927 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800928 * {@link #UNSUPPORTED} on devices where statistics aren't available.
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700929 * <p>
930 * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
931 * report traffic statistics for the calling UID. It will return
932 * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
933 * historical network statistics belonging to other UIDs, use
934 * {@link NetworkStatsManager}.
Ken Shirriffae521152009-12-07 15:56:05 -0800935 *
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800936 * @see android.os.Process#myUid()
937 * @see android.content.pm.ApplicationInfo#uid
Ken Shirriffae521152009-12-07 15:56:05 -0800938 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800939 public static long getUidRxBytes(int uid) {
Chenbo Fengd80a6ed2019-06-17 16:22:28 -0700940 try {
941 return getStatsService().getUidStats(uid, TYPE_RX_BYTES);
942 } catch (RemoteException e) {
943 throw e.rethrowFromSystemServer();
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700944 }
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800945 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800946
947 /**
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800948 * Return number of packets transmitted by the given UID since device boot.
949 * Counts packets across all network interfaces, and always increases
950 * monotonically since device boot. Statistics are measured at the network
951 * layer, so they include both TCP and UDP usage.
952 * <p>
Dianne Hackborne9d72072013-02-25 15:55:37 -0800953 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800954 * {@link #UNSUPPORTED} on devices where statistics aren't available.
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700955 * <p>
956 * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
957 * report traffic statistics for the calling UID. It will return
958 * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
959 * historical network statistics belonging to other UIDs, use
960 * {@link NetworkStatsManager}.
Ashish Sharmadf852d82011-01-27 15:52:38 -0800961 *
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800962 * @see android.os.Process#myUid()
963 * @see android.content.pm.ApplicationInfo#uid
Ashish Sharmadf852d82011-01-27 15:52:38 -0800964 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800965 public static long getUidTxPackets(int uid) {
Chenbo Fengd80a6ed2019-06-17 16:22:28 -0700966 try {
967 return getStatsService().getUidStats(uid, TYPE_TX_PACKETS);
968 } catch (RemoteException e) {
969 throw e.rethrowFromSystemServer();
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700970 }
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800971 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800972
973 /**
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800974 * Return number of packets received by the given UID since device boot.
975 * Counts packets across all network interfaces, and always increases
976 * monotonically since device boot. Statistics are measured at the network
977 * layer, so they include both TCP and UDP usage.
978 * <p>
Dianne Hackborne9d72072013-02-25 15:55:37 -0800979 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800980 * {@link #UNSUPPORTED} on devices where statistics aren't available.
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700981 * <p>
982 * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
983 * report traffic statistics for the calling UID. It will return
984 * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
985 * historical network statistics belonging to other UIDs, use
986 * {@link NetworkStatsManager}.
Ashish Sharmadf852d82011-01-27 15:52:38 -0800987 *
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800988 * @see android.os.Process#myUid()
989 * @see android.content.pm.ApplicationInfo#uid
Ashish Sharmadf852d82011-01-27 15:52:38 -0800990 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800991 public static long getUidRxPackets(int uid) {
Chenbo Fengd80a6ed2019-06-17 16:22:28 -0700992 try {
993 return getStatsService().getUidStats(uid, TYPE_RX_PACKETS);
994 } catch (RemoteException e) {
995 throw e.rethrowFromSystemServer();
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700996 }
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800997 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800998
999 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -08001000 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001001 * transport layer statistics are no longer available, and will
1002 * always return {@link #UNSUPPORTED}.
1003 * @see #getUidTxBytes(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -08001004 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001005 @Deprecated
1006 public static long getUidTcpTxBytes(int uid) {
1007 return UNSUPPORTED;
1008 }
Ashish Sharmadf852d82011-01-27 15:52:38 -08001009
1010 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -08001011 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001012 * transport layer statistics are no longer available, and will
1013 * always return {@link #UNSUPPORTED}.
1014 * @see #getUidRxBytes(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -08001015 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001016 @Deprecated
1017 public static long getUidTcpRxBytes(int uid) {
1018 return UNSUPPORTED;
1019 }
Ashish Sharmadf852d82011-01-27 15:52:38 -08001020
1021 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -08001022 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001023 * transport layer statistics are no longer available, and will
1024 * always return {@link #UNSUPPORTED}.
1025 * @see #getUidTxBytes(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -08001026 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001027 @Deprecated
1028 public static long getUidUdpTxBytes(int uid) {
1029 return UNSUPPORTED;
1030 }
Ashish Sharmadf852d82011-01-27 15:52:38 -08001031
1032 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -08001033 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001034 * transport layer statistics are no longer available, and will
1035 * always return {@link #UNSUPPORTED}.
1036 * @see #getUidRxBytes(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -08001037 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001038 @Deprecated
1039 public static long getUidUdpRxBytes(int uid) {
1040 return UNSUPPORTED;
1041 }
Ashish Sharmadf852d82011-01-27 15:52:38 -08001042
1043 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -08001044 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001045 * transport layer statistics are no longer available, and will
1046 * always return {@link #UNSUPPORTED}.
1047 * @see #getUidTxPackets(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -08001048 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001049 @Deprecated
1050 public static long getUidTcpTxSegments(int uid) {
1051 return UNSUPPORTED;
1052 }
Ashish Sharmadf852d82011-01-27 15:52:38 -08001053
1054 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -08001055 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001056 * transport layer statistics are no longer available, and will
1057 * always return {@link #UNSUPPORTED}.
1058 * @see #getUidRxPackets(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -08001059 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001060 @Deprecated
1061 public static long getUidTcpRxSegments(int uid) {
1062 return UNSUPPORTED;
1063 }
Ashish Sharmadf852d82011-01-27 15:52:38 -08001064
Ashish Sharmadf852d82011-01-27 15:52:38 -08001065 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -08001066 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001067 * transport layer statistics are no longer available, and will
1068 * always return {@link #UNSUPPORTED}.
1069 * @see #getUidTxPackets(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -08001070 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001071 @Deprecated
1072 public static long getUidUdpTxPackets(int uid) {
1073 return UNSUPPORTED;
1074 }
Ashish Sharmadf852d82011-01-27 15:52:38 -08001075
1076 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -08001077 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001078 * transport layer statistics are no longer available, and will
1079 * always return {@link #UNSUPPORTED}.
1080 * @see #getUidRxPackets(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -08001081 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001082 @Deprecated
1083 public static long getUidUdpRxPackets(int uid) {
1084 return UNSUPPORTED;
1085 }
Jeff Sharkey33936ac2011-05-17 14:55:15 -07001086
1087 /**
1088 * Return detailed {@link NetworkStats} for the current UID. Requires no
1089 * special permission.
1090 */
Jeff Sharkey7407e092011-07-19 23:47:12 -07001091 private static NetworkStats getDataLayerSnapshotForUid(Context context) {
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -07001092 // TODO: take snapshot locally, since proc file is now visible
Jeff Sharkey33936ac2011-05-17 14:55:15 -07001093 final int uid = android.os.Process.myUid();
1094 try {
Jeff Sharkey8308b9b2012-04-10 19:48:07 -07001095 return getStatsService().getDataLayerSnapshotForUid(uid);
Jeff Sharkey33936ac2011-05-17 14:55:15 -07001096 } catch (RemoteException e) {
Jeff Sharkeybc08d072016-02-26 13:03:01 -07001097 throw e.rethrowFromSystemServer();
Jeff Sharkey33936ac2011-05-17 14:55:15 -07001098 }
1099 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -07001100
1101 /**
1102 * Return set of any ifaces associated with mobile networks since boot.
1103 * Interfaces are never removed from this list, so counters should always be
1104 * monotonic.
1105 */
Chalard Jean3cfb4992019-04-09 15:46:21 +09001106 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey8308b9b2012-04-10 19:48:07 -07001107 private static String[] getMobileIfaces() {
1108 try {
1109 return getStatsService().getMobileIfaces();
1110 } catch (RemoteException e) {
Jeff Sharkeybc08d072016-02-26 13:03:01 -07001111 throw e.rethrowFromSystemServer();
Jeff Sharkey8308b9b2012-04-10 19:48:07 -07001112 }
1113 }
1114
junyulaiea236322020-10-06 11:59:56 +08001115 // NOTE: keep these in sync with {@code com_android_server_net_NetworkStatsService.cpp}.
1116 /** {@hide} */
1117 public static final int TYPE_RX_BYTES = 0;
1118 /** {@hide} */
1119 public static final int TYPE_RX_PACKETS = 1;
1120 /** {@hide} */
1121 public static final int TYPE_TX_BYTES = 2;
1122 /** {@hide} */
1123 public static final int TYPE_TX_PACKETS = 3;
Ken Shirriffae521152009-12-07 15:56:05 -08001124}