blob: d50908216464b69d5fc2cdb4a8c3f40f4e25bea9 [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 Lai8efe3482022-01-17 17:05:30 +000019import static android.annotation.SystemApi.Client.MODULE_LIBRARIES;
20
Aaron Huangb0db4fd2019-09-27 22:31:22 +080021import android.annotation.NonNull;
Jeff Sharkeyf5c1f302017-11-29 11:18:23 -070022import android.annotation.SuppressLint;
Christopher Tate5a1878d2014-08-06 14:19:56 -070023import android.annotation.SystemApi;
Benedict Wong8231eaf2017-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 Satayevaf1eb472019-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 Lai6f39e802022-01-19 08:33:21 +000031import android.os.Binder;
Chalard Jean4722cf12019-04-09 15:46:21 +090032import android.os.Build;
Jeff Sharkey33936ac2011-05-17 14:55:15 -070033import android.os.RemoteException;
Lorenzo Colitti81b707f2022-01-29 21:07:33 +090034import android.os.StrictMode;
Junyu Lai82a33b82022-01-25 07:40:06 +000035import android.util.Log;
Jeff Sharkey33936ac2011-05-17 14:55:15 -070036
Jeff Sharkeyf5c1f302017-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 Colitti81b707f2022-01-29 21:07:33 +090056 static {
57 System.loadLibrary("framework-connectivity-tiramisu-jni");
58 }
59
Junyu Laid3cb2ba2021-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 Lai989b2122021-12-27 13:56:59 +000066 /** @hide @deprecated use {@code DataUnit} instead to clarify SI-vs-IEC */
Jeff Sharkey69f6f062018-01-07 16:47:31 -070067 @Deprecated
Jeff Sharkey94a315c2012-02-03 14:50:07 -080068 public static final long KB_IN_BYTES = 1024;
Junyu Lai989b2122021-12-27 13:56:59 +000069 /** @hide @deprecated use {@code DataUnit} instead to clarify SI-vs-IEC */
Jeff Sharkey69f6f062018-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 Lai989b2122021-12-27 13:56:59 +000072 /** @hide @deprecated use {@code DataUnit} instead to clarify SI-vs-IEC */
Jeff Sharkey69f6f062018-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 Lai989b2122021-12-27 13:56:59 +000075 /** @hide @deprecated use {@code DataUnit} instead to clarify SI-vs-IEC */
Jeff Sharkey69f6f062018-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 Lai989b2122021-12-27 13:56:59 +000078 /** @hide @deprecated use {@code DataUnit} instead to clarify SI-vs-IEC */
Jeff Sharkey69f6f062018-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 */
junyulai10a00a22019-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 Jean65c39682019-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 Sharkey63ee5282017-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 Sharkey63ee5282017-08-11 15:04:12 -0600170 public static final int TAG_SYSTEM_APP = 0xFFFFFF05;
Jeff Sharkey38fd65b2017-06-26 19:50:41 -0600171
Chalard Jean65c39682019-04-09 11:16:56 +0900172 // TODO : remove this constant when Wifi code is updated
Jeff Sharkey38fd65b2017-06-26 19:50:41 -0600173 /** @hide */
Jeff Sharkey38fd65b2017-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 Jean4722cf12019-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 Lai6f39e802022-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 Wong8231eaf2017-12-03 19:42:36 -0800198 private static final String LOOPBACK_IFACE = "lo";
199
Jeff Sharkey33936ac2011-05-17 14:55:15 -0700200 /**
Junyu Lai6f39e802022-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 */
junyulai5dc94ed2022-03-01 16:53:28 +0800208 @SystemApi(client = MODULE_LIBRARIES)
Junyu Lai6f39e802022-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 Lai82a33b82022-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 Lai6f39e802022-01-19 08:33:21 +0000224 sStatsService = statsManager.getBinder();
225 }
226
227 /**
Junyu Lai8efe3482022-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 Colitti81b707f2022-01-29 21:07:33 +0900236 dalvik.system.SocketTagger.set(new SocketTagger());
Junyu Lai8efe3482022-01-17 17:05:30 +0000237 }
238
Lorenzo Colitti81b707f2022-01-29 21:07:33 +0900239 private static class SocketTagger extends dalvik.system.SocketTagger {
240
Subhajeet Muhuri250a7f22022-09-13 16:55:10 +0530241 private static final boolean LOGD = false;
Lorenzo Colitti81b707f2022-01-29 21:07:33 +0900242
243 SocketTagger() {
244 }
245
246 @Override
247 public void tag(FileDescriptor fd) throws SocketException {
248 final UidTag tagInfo = sThreadUidTag.get();
249 if (LOGD) {
250 Log.d(TAG, "tagSocket(" + fd.getInt$() + ") with statsTag=0x"
251 + Integer.toHexString(tagInfo.tag) + ", statsUid=" + tagInfo.uid);
252 }
253 if (tagInfo.tag == -1) {
254 StrictMode.noteUntaggedSocket();
255 }
256
257 if (tagInfo.tag == -1 && tagInfo.uid == -1) return;
258 final int errno = native_tagSocketFd(fd, tagInfo.tag, tagInfo.uid);
259 if (errno < 0) {
260 Log.i(TAG, "tagSocketFd(" + fd.getInt$() + ", "
261 + tagInfo.tag + ", "
262 + tagInfo.uid + ") failed with errno" + errno);
263 }
264 }
265
266 @Override
267 public void untag(FileDescriptor fd) throws SocketException {
268 if (LOGD) {
269 Log.i(TAG, "untagSocket(" + fd.getInt$() + ")");
270 }
271
272 final UidTag tagInfo = sThreadUidTag.get();
273 if (tagInfo.tag == -1 && tagInfo.uid == -1) return;
274
275 final int errno = native_untagSocketFd(fd);
276 if (errno < 0) {
277 Log.w(TAG, "untagSocket(" + fd.getInt$() + ") failed with errno " + errno);
278 }
279 }
280 }
281
282 private static native int native_tagSocketFd(FileDescriptor fd, int tag, int uid);
283 private static native int native_untagSocketFd(FileDescriptor fd);
284
285 private static class UidTag {
286 public int tag = -1;
287 public int uid = -1;
288 }
289
290 private static ThreadLocal<UidTag> sThreadUidTag = new ThreadLocal<UidTag>() {
291 @Override
292 protected UidTag initialValue() {
293 return new UidTag();
294 }
295 };
296
Junyu Lai8efe3482022-01-17 17:05:30 +0000297 /**
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700298 * Set active tag to use when accounting {@link Socket} traffic originating
299 * from the current thread. Only one active tag per thread is supported.
300 * <p>
301 * Changes only take effect during subsequent calls to
302 * {@link #tagSocket(Socket)}.
Jeff Sharkey987f5ff2011-09-16 01:52:49 -0700303 * <p>
304 * Tags between {@code 0xFFFFFF00} and {@code 0xFFFFFFFF} are reserved and
305 * used internally by system services like {@link DownloadManager} when
306 * performing traffic on behalf of an application.
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700307 *
308 * @see #clearThreadStatsTag()
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700309 */
Jeff Sharkey92790062011-06-24 17:05:24 -0700310 public static void setThreadStatsTag(int tag) {
Lorenzo Colitti81b707f2022-01-29 21:07:33 +0900311 getAndSetThreadStatsTag(tag);
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700312 }
313
Jeff Sharkey92790062011-06-24 17:05:24 -0700314 /**
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600315 * Set active tag to use when accounting {@link Socket} traffic originating
Jeff Sharkey289eac12017-01-19 11:55:54 -0700316 * from the current thread. Only one active tag per thread is supported.
317 * <p>
318 * Changes only take effect during subsequent calls to
319 * {@link #tagSocket(Socket)}.
320 * <p>
321 * Tags between {@code 0xFFFFFF00} and {@code 0xFFFFFFFF} are reserved and
322 * used internally by system services like {@link DownloadManager} when
323 * performing traffic on behalf of an application.
324 *
325 * @return the current tag for the calling thread, which can be used to
326 * restore any existing values after a nested operation is finished
327 */
328 public static int getAndSetThreadStatsTag(int tag) {
Lorenzo Colitti81b707f2022-01-29 21:07:33 +0900329 final int old = sThreadUidTag.get().tag;
330 sThreadUidTag.get().tag = tag;
331 return old;
Jeff Sharkey289eac12017-01-19 11:55:54 -0700332 }
333
334 /**
335 * Set active tag to use when accounting {@link Socket} traffic originating
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600336 * from the current thread. The tag used internally is well-defined to
337 * distinguish all backup-related traffic.
338 *
Christopher Tate5a1878d2014-08-06 14:19:56 -0700339 * @hide
340 */
341 @SystemApi
342 public static void setThreadStatsTagBackup() {
343 setThreadStatsTag(TAG_SYSTEM_BACKUP);
344 }
345
346 /**
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600347 * Set active tag to use when accounting {@link Socket} traffic originating
348 * from the current thread. The tag used internally is well-defined to
349 * distinguish all restore-related traffic.
350 *
Christopher Tatec1c71fd2015-11-10 10:49:20 -0800351 * @hide
352 */
353 @SystemApi
354 public static void setThreadStatsTagRestore() {
355 setThreadStatsTag(TAG_SYSTEM_RESTORE);
356 }
357
358 /**
Jeff Sharkey38fd65b2017-06-26 19:50:41 -0600359 * Set active tag to use when accounting {@link Socket} traffic originating
360 * from the current thread. The tag used internally is well-defined to
Jeff Sharkey63ee5282017-08-11 15:04:12 -0600361 * distinguish all code (typically APKs) downloaded by an app store on
362 * behalf of the app, such as updates.
Jeff Sharkey38fd65b2017-06-26 19:50:41 -0600363 *
364 * @hide
365 */
366 @SystemApi
Jeff Sharkey63ee5282017-08-11 15:04:12 -0600367 public static void setThreadStatsTagApp() {
368 setThreadStatsTag(TAG_SYSTEM_APP);
Jeff Sharkey38fd65b2017-06-26 19:50:41 -0600369 }
370
371 /**
Junyu Lai2d34f3e2022-01-18 02:46:23 +0000372 * Set active tag to use when accounting {@link Socket} traffic originating
373 * from the current thread. The tag used internally is well-defined to
374 * distinguish all download provider traffic.
375 *
376 * @hide
377 */
junyulai5dc94ed2022-03-01 16:53:28 +0800378 @SystemApi(client = MODULE_LIBRARIES)
Junyu Lai2d34f3e2022-01-18 02:46:23 +0000379 public static void setThreadStatsTagDownload() {
380 setThreadStatsTag(TAG_SYSTEM_DOWNLOAD);
381 }
382
383 /**
Alon Albert2c295f02011-07-19 11:16:09 +0300384 * Get the active tag used when accounting {@link Socket} traffic originating
385 * from the current thread. Only one active tag per thread is supported.
386 * {@link #tagSocket(Socket)}.
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700387 *
388 * @see #setThreadStatsTag(int)
Alon Albert2c295f02011-07-19 11:16:09 +0300389 */
390 public static int getThreadStatsTag() {
Lorenzo Colitti81b707f2022-01-29 21:07:33 +0900391 return sThreadUidTag.get().tag;
Alon Albert2c295f02011-07-19 11:16:09 +0300392 }
393
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700394 /**
395 * Clear any active tag set to account {@link Socket} traffic originating
396 * from the current thread.
397 *
398 * @see #setThreadStatsTag(int)
399 */
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700400 public static void clearThreadStatsTag() {
Lorenzo Colitti81b707f2022-01-29 21:07:33 +0900401 sThreadUidTag.get().tag = -1;
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700402 }
403
404 /**
405 * Set specific UID to use when accounting {@link Socket} traffic
406 * originating from the current thread. Designed for use when performing an
Jeff Sharkey8d66e652018-03-26 13:11:33 -0600407 * operation on behalf of another application, or when another application
408 * is performing operations on your behalf.
409 * <p>
410 * Any app can <em>accept</em> blame for traffic performed on a socket
411 * originally created by another app by calling this method with the
412 * {@link android.system.Os#getuid()} value. However, only apps holding the
413 * {@code android.Manifest.permission#UPDATE_DEVICE_STATS} permission may
414 * <em>assign</em> blame to another UIDs.
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700415 * <p>
416 * Changes only take effect during subsequent calls to
417 * {@link #tagSocket(Socket)}.
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700418 */
Aurimas Liutikas0caeaa32020-11-12 18:29:11 -0800419 @SuppressLint("RequiresPermission")
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700420 public static void setThreadStatsUid(int uid) {
Lorenzo Colitti81b707f2022-01-29 21:07:33 +0900421 sThreadUidTag.get().uid = uid;
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700422 }
423
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600424 /**
Jeff Sharkey8d66e652018-03-26 13:11:33 -0600425 * Get the active UID used when accounting {@link Socket} traffic originating
426 * from the current thread. Only one active tag per thread is supported.
427 * {@link #tagSocket(Socket)}.
428 *
429 * @see #setThreadStatsUid(int)
430 */
431 public static int getThreadStatsUid() {
Lorenzo Colitti81b707f2022-01-29 21:07:33 +0900432 return sThreadUidTag.get().uid;
Jeff Sharkey8d66e652018-03-26 13:11:33 -0600433 }
434
435 /**
Jeff Sharkeyf5c1f302017-11-29 11:18:23 -0700436 * Set specific UID to use when accounting {@link Socket} traffic
437 * originating from the current thread as the calling UID. Designed for use
438 * when another application is performing operations on your behalf.
439 * <p>
440 * Changes only take effect during subsequent calls to
441 * {@link #tagSocket(Socket)}.
Jeff Sharkey8d66e652018-03-26 13:11:33 -0600442 *
443 * @removed
444 * @deprecated use {@link #setThreadStatsUid(int)} instead.
Jeff Sharkeyf5c1f302017-11-29 11:18:23 -0700445 */
Jeff Sharkey8d66e652018-03-26 13:11:33 -0600446 @Deprecated
Jeff Sharkeyf5c1f302017-11-29 11:18:23 -0700447 public static void setThreadStatsUidSelf() {
448 setThreadStatsUid(android.os.Process.myUid());
449 }
450
451 /**
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600452 * Clear any active UID set to account {@link Socket} traffic originating
453 * from the current thread.
454 *
455 * @see #setThreadStatsUid(int)
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600456 */
Aurimas Liutikas0caeaa32020-11-12 18:29:11 -0800457 @SuppressLint("RequiresPermission")
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700458 public static void clearThreadStatsUid() {
Lorenzo Colitti81b707f2022-01-29 21:07:33 +0900459 setThreadStatsUid(-1);
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700460 }
461
462 /**
463 * Tag the given {@link Socket} with any statistics parameters active for
464 * the current thread. Subsequent calls always replace any existing
465 * parameters. When finished, call {@link #untagSocket(Socket)} to remove
466 * statistics parameters.
467 *
Jeff Sharkey92790062011-06-24 17:05:24 -0700468 * @see #setThreadStatsTag(int)
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700469 */
junyulai5dc94ed2022-03-01 16:53:28 +0800470 public static void tagSocket(@NonNull Socket socket) throws SocketException {
Jesse Wilsonb05f41c2011-06-28 19:06:31 -0700471 SocketTagger.get().tag(socket);
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700472 }
473
474 /**
475 * Remove any statistics parameters from the given {@link Socket}.
koprivab02b6402018-07-23 18:19:39 -0700476 * <p>
477 * In Android 8.1 (API level 27) and lower, a socket is automatically
478 * untagged when it's sent to another process using binder IPC with a
479 * {@code ParcelFileDescriptor} container. In Android 9.0 (API level 28)
480 * and higher, the socket tag is kept when the socket is sent to another
481 * process using binder IPC. You can mimic the previous behavior by
482 * calling {@code untagSocket()} before sending the socket to another
483 * process.
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700484 */
junyulai5dc94ed2022-03-01 16:53:28 +0800485 public static void untagSocket(@NonNull Socket socket) throws SocketException {
Jesse Wilsonb05f41c2011-06-28 19:06:31 -0700486 SocketTagger.get().untag(socket);
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700487 }
488
489 /**
Jeff Sharkey7b124cb2015-12-04 15:21:52 -0700490 * Tag the given {@link DatagramSocket} with any statistics parameters
491 * active for the current thread. Subsequent calls always replace any
492 * existing parameters. When finished, call
493 * {@link #untagDatagramSocket(DatagramSocket)} to remove statistics
494 * parameters.
495 *
496 * @see #setThreadStatsTag(int)
Jeff Sharkey7b124cb2015-12-04 15:21:52 -0700497 */
junyulai5dc94ed2022-03-01 16:53:28 +0800498 public static void tagDatagramSocket(@NonNull DatagramSocket socket) throws SocketException {
Jeff Sharkey7b124cb2015-12-04 15:21:52 -0700499 SocketTagger.get().tag(socket);
500 }
501
502 /**
503 * Remove any statistics parameters from the given {@link DatagramSocket}.
504 */
junyulai5dc94ed2022-03-01 16:53:28 +0800505 public static void untagDatagramSocket(@NonNull DatagramSocket socket) throws SocketException {
Jeff Sharkey7b124cb2015-12-04 15:21:52 -0700506 SocketTagger.get().untag(socket);
507 }
508
509 /**
Jeff Sharkeyf5c1f302017-11-29 11:18:23 -0700510 * Tag the given {@link FileDescriptor} socket with any statistics
511 * parameters active for the current thread. Subsequent calls always replace
512 * any existing parameters. When finished, call
513 * {@link #untagFileDescriptor(FileDescriptor)} to remove statistics
514 * parameters.
515 *
516 * @see #setThreadStatsTag(int)
517 */
junyulai5dc94ed2022-03-01 16:53:28 +0800518 public static void tagFileDescriptor(@NonNull FileDescriptor fd) throws IOException {
Jeff Sharkeyf5c1f302017-11-29 11:18:23 -0700519 SocketTagger.get().tag(fd);
520 }
521
522 /**
523 * Remove any statistics parameters from the given {@link FileDescriptor}
524 * socket.
525 */
junyulai5dc94ed2022-03-01 16:53:28 +0800526 public static void untagFileDescriptor(@NonNull FileDescriptor fd) throws IOException {
Jeff Sharkeyf5c1f302017-11-29 11:18:23 -0700527 SocketTagger.get().untag(fd);
528 }
529
530 /**
Jeff Sharkey33936ac2011-05-17 14:55:15 -0700531 * Start profiling data usage for current UID. Only one profiling session
532 * can be active at a time.
533 *
534 * @hide
535 */
536 public static void startDataProfiling(Context context) {
537 synchronized (sProfilingLock) {
538 if (sActiveProfilingStart != null) {
539 throw new IllegalStateException("already profiling data");
540 }
541
542 // take snapshot in time; we calculate delta later
Jeff Sharkey7407e092011-07-19 23:47:12 -0700543 sActiveProfilingStart = getDataLayerSnapshotForUid(context);
Jeff Sharkey33936ac2011-05-17 14:55:15 -0700544 }
545 }
546
547 /**
548 * Stop profiling data usage for current UID.
549 *
550 * @return Detailed {@link NetworkStats} of data that occurred since last
551 * {@link #startDataProfiling(Context)} call.
552 * @hide
553 */
554 public static NetworkStats stopDataProfiling(Context context) {
555 synchronized (sProfilingLock) {
556 if (sActiveProfilingStart == null) {
557 throw new IllegalStateException("not profiling data");
558 }
559
Jeff Sharkeyef7bded2012-01-10 17:24:44 -0800560 // subtract starting values and return delta
561 final NetworkStats profilingStop = getDataLayerSnapshotForUid(context);
562 final NetworkStats profilingDelta = NetworkStats.subtract(
Jeff Sharkeybfe82682012-01-11 18:38:16 -0800563 profilingStop, sActiveProfilingStart, null, null);
Jeff Sharkeyef7bded2012-01-10 17:24:44 -0800564 sActiveProfilingStart = null;
565 return profilingDelta;
Jeff Sharkey33936ac2011-05-17 14:55:15 -0700566 }
567 }
568
569 /**
Jeff Sharkey60ca0232011-08-24 15:42:09 -0700570 * Increment count of network operations performed under the accounting tag
571 * currently active on the calling thread. This can be used to derive
572 * bytes-per-operation.
573 *
574 * @param operationCount Number of operations to increment count by.
575 */
576 public static void incrementOperationCount(int operationCount) {
577 final int tag = getThreadStatsTag();
578 incrementOperationCount(tag, operationCount);
579 }
580
581 /**
Jeff Sharkey7407e092011-07-19 23:47:12 -0700582 * Increment count of network operations performed under the given
583 * accounting tag. This can be used to derive bytes-per-operation.
584 *
585 * @param tag Accounting tag used in {@link #setThreadStatsTag(int)}.
586 * @param operationCount Number of operations to increment count by.
587 */
588 public static void incrementOperationCount(int tag, int operationCount) {
Jeff Sharkey7407e092011-07-19 23:47:12 -0700589 final int uid = android.os.Process.myUid();
590 try {
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700591 getStatsService().incrementOperationCount(uid, tag, operationCount);
Jeff Sharkey7407e092011-07-19 23:47:12 -0700592 } catch (RemoteException e) {
Jeff Sharkeybc08d072016-02-26 13:03:01 -0700593 throw e.rethrowFromSystemServer();
Jeff Sharkey7407e092011-07-19 23:47:12 -0700594 }
595 }
596
Jeff Sharkey920d9042012-04-06 11:12:08 -0700597 /** {@hide} */
598 public static void closeQuietly(INetworkStatsSession session) {
599 // TODO: move to NetworkStatsService once it exists
600 if (session != null) {
601 try {
602 session.close();
603 } catch (RuntimeException rethrown) {
604 throw rethrown;
605 } catch (Exception ignored) {
606 }
607 }
608 }
609
Chenbo Feng7f880c92018-01-25 11:43:52 -0800610 private static long addIfSupported(long stat) {
611 return (stat == UNSUPPORTED) ? 0 : stat;
612 }
613
Jeff Sharkey7407e092011-07-19 23:47:12 -0700614 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700615 * Return number of packets transmitted across mobile networks since device
616 * boot. Counts packets across all mobile network interfaces, and always
617 * increases monotonically since device boot. Statistics are measured at the
618 * network layer, so they include both TCP and UDP usage.
619 * <p>
620 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
621 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800622 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700623 public static long getMobileTxPackets() {
624 long total = 0;
625 for (String iface : getMobileIfaces()) {
Chenbo Feng7f880c92018-01-25 11:43:52 -0800626 total += addIfSupported(getTxPackets(iface));
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700627 }
628 return total;
629 }
Ken Shirriffae521152009-12-07 15:56:05 -0800630
631 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700632 * Return number of packets received across mobile networks since device
633 * boot. Counts packets across all mobile network interfaces, and always
634 * increases monotonically since device boot. Statistics are measured at the
635 * network layer, so they include both TCP and UDP usage.
636 * <p>
637 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
638 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800639 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700640 public static long getMobileRxPackets() {
641 long total = 0;
642 for (String iface : getMobileIfaces()) {
Chenbo Feng7f880c92018-01-25 11:43:52 -0800643 total += addIfSupported(getRxPackets(iface));
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700644 }
645 return total;
646 }
Ken Shirriffae521152009-12-07 15:56:05 -0800647
648 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700649 * Return number of bytes transmitted across mobile networks since device
650 * boot. Counts packets across all mobile network interfaces, and always
651 * increases monotonically since device boot. Statistics are measured at the
652 * network layer, so they include both TCP and UDP usage.
653 * <p>
654 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
655 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800656 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700657 public static long getMobileTxBytes() {
658 long total = 0;
659 for (String iface : getMobileIfaces()) {
Chenbo Feng7f880c92018-01-25 11:43:52 -0800660 total += addIfSupported(getTxBytes(iface));
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700661 }
662 return total;
663 }
Ken Shirriffae521152009-12-07 15:56:05 -0800664
665 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700666 * Return number of bytes received across mobile networks since device boot.
667 * Counts packets across all mobile network interfaces, and always increases
668 * monotonically since device boot. Statistics are measured at the network
669 * layer, so they include both TCP and UDP usage.
670 * <p>
671 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
672 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800673 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700674 public static long getMobileRxBytes() {
675 long total = 0;
676 for (String iface : getMobileIfaces()) {
Chenbo Feng7f880c92018-01-25 11:43:52 -0800677 total += addIfSupported(getRxBytes(iface));
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700678 }
679 return total;
680 }
Ken Shirriffae521152009-12-07 15:56:05 -0800681
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800682 /** {@hide} */
Mathew Inwood5c74a0f2020-11-04 09:29:36 +0000683 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800684 public static long getMobileTcpRxPackets() {
Maciej Żenczykowski66645a82023-08-12 08:26:44 +0000685 return UNSUPPORTED;
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800686 }
687
688 /** {@hide} */
Mathew Inwood5c74a0f2020-11-04 09:29:36 +0000689 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800690 public static long getMobileTcpTxPackets() {
Maciej Żenczykowski66645a82023-08-12 08:26:44 +0000691 return UNSUPPORTED;
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800692 }
693
Aaron Huangb0db4fd2019-09-27 22:31:22 +0800694 /**
junyulai01f60b22020-09-29 14:19:24 +0800695 * Return the number of packets transmitted on the specified interface since the interface
696 * was created. Statistics are measured at the network layer, so both TCP and
Aaron Huangb0db4fd2019-09-27 22:31:22 +0800697 * UDP usage are included.
698 *
junyulai01f60b22020-09-29 14:19:24 +0800699 * Note that the returned values are partial statistics that do not count data from several
700 * sources and do not apply several adjustments that are necessary for correctness, such
701 * as adjusting for VPN apps, IPv6-in-IPv4 translation, etc. These values can be used to
702 * determine whether traffic is being transferred on the specific interface but are not a
703 * substitute for the more accurate statistics provided by the {@link NetworkStatsManager}
704 * APIs.
705 *
Aaron Huangb0db4fd2019-09-27 22:31:22 +0800706 * @param iface The name of the interface.
707 * @return The number of transmitted packets.
708 */
709 public static long getTxPackets(@NonNull String iface) {
Chenbo Feng65b99192017-11-14 17:54:17 -0800710 try {
711 return getStatsService().getIfaceStats(iface, TYPE_TX_PACKETS);
712 } catch (RemoteException e) {
713 throw e.rethrowFromSystemServer();
714 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700715 }
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800716
Aaron Huangb0db4fd2019-09-27 22:31:22 +0800717 /**
junyulai01f60b22020-09-29 14:19:24 +0800718 * Return the number of packets received on the specified interface since the interface was
719 * created. Statistics are measured at the network layer, so both TCP
Aaron Huangb0db4fd2019-09-27 22:31:22 +0800720 * and UDP usage are included.
721 *
junyulai01f60b22020-09-29 14:19:24 +0800722 * Note that the returned values are partial statistics that do not count data from several
723 * sources and do not apply several adjustments that are necessary for correctness, such
724 * as adjusting for VPN apps, IPv6-in-IPv4 translation, etc. These values can be used to
725 * determine whether traffic is being transferred on the specific interface but are not a
726 * substitute for the more accurate statistics provided by the {@link NetworkStatsManager}
727 * APIs.
728 *
Aaron Huangb0db4fd2019-09-27 22:31:22 +0800729 * @param iface The name of the interface.
730 * @return The number of received packets.
731 */
732 public static long getRxPackets(@NonNull String iface) {
Chenbo Feng65b99192017-11-14 17:54:17 -0800733 try {
734 return getStatsService().getIfaceStats(iface, TYPE_RX_PACKETS);
735 } catch (RemoteException e) {
736 throw e.rethrowFromSystemServer();
737 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700738 }
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800739
junyulai01f60b22020-09-29 14:19:24 +0800740 /**
741 * Return the number of bytes transmitted on the specified interface since the interface
742 * was created. Statistics are measured at the network layer, so both TCP and
743 * UDP usage are included.
744 *
745 * Note that the returned values are partial statistics that do not count data from several
746 * sources and do not apply several adjustments that are necessary for correctness, such
747 * as adjusting for VPN apps, IPv6-in-IPv4 translation, etc. These values can be used to
748 * determine whether traffic is being transferred on the specific interface but are not a
749 * substitute for the more accurate statistics provided by the {@link NetworkStatsManager}
750 * APIs.
751 *
752 * @param iface The name of the interface.
753 * @return The number of transmitted bytes.
754 */
755 public static long getTxBytes(@NonNull String iface) {
Chenbo Feng65b99192017-11-14 17:54:17 -0800756 try {
757 return getStatsService().getIfaceStats(iface, TYPE_TX_BYTES);
758 } catch (RemoteException e) {
759 throw e.rethrowFromSystemServer();
760 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700761 }
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800762
junyulai01f60b22020-09-29 14:19:24 +0800763 /**
764 * Return the number of bytes received on the specified interface since the interface
765 * was created. Statistics are measured at the network layer, so both TCP
766 * and UDP usage are included.
767 *
768 * Note that the returned values are partial statistics that do not count data from several
769 * sources and do not apply several adjustments that are necessary for correctness, such
770 * as adjusting for VPN apps, IPv6-in-IPv4 translation, etc. These values can be used to
771 * determine whether traffic is being transferred on the specific interface but are not a
772 * substitute for the more accurate statistics provided by the {@link NetworkStatsManager}
773 * APIs.
774 *
775 * @param iface The name of the interface.
776 * @return The number of received bytes.
777 */
778 public static long getRxBytes(@NonNull String iface) {
Chenbo Feng65b99192017-11-14 17:54:17 -0800779 try {
780 return getStatsService().getIfaceStats(iface, TYPE_RX_BYTES);
781 } catch (RemoteException e) {
782 throw e.rethrowFromSystemServer();
783 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700784 }
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800785
Benedict Wong8231eaf2017-12-03 19:42:36 -0800786 /** {@hide} */
787 @TestApi
788 public static long getLoopbackTxPackets() {
Chenbo Feng65b99192017-11-14 17:54:17 -0800789 try {
790 return getStatsService().getIfaceStats(LOOPBACK_IFACE, TYPE_TX_PACKETS);
791 } catch (RemoteException e) {
792 throw e.rethrowFromSystemServer();
793 }
Benedict Wong8231eaf2017-12-03 19:42:36 -0800794 }
795
796 /** {@hide} */
797 @TestApi
798 public static long getLoopbackRxPackets() {
Chenbo Feng65b99192017-11-14 17:54:17 -0800799 try {
800 return getStatsService().getIfaceStats(LOOPBACK_IFACE, TYPE_RX_PACKETS);
801 } catch (RemoteException e) {
802 throw e.rethrowFromSystemServer();
803 }
Benedict Wong8231eaf2017-12-03 19:42:36 -0800804 }
805
806 /** {@hide} */
807 @TestApi
808 public static long getLoopbackTxBytes() {
Chenbo Feng65b99192017-11-14 17:54:17 -0800809 try {
810 return getStatsService().getIfaceStats(LOOPBACK_IFACE, TYPE_TX_BYTES);
811 } catch (RemoteException e) {
812 throw e.rethrowFromSystemServer();
813 }
Benedict Wong8231eaf2017-12-03 19:42:36 -0800814 }
815
816 /** {@hide} */
817 @TestApi
818 public static long getLoopbackRxBytes() {
Chenbo Feng65b99192017-11-14 17:54:17 -0800819 try {
820 return getStatsService().getIfaceStats(LOOPBACK_IFACE, TYPE_RX_BYTES);
821 } catch (RemoteException e) {
822 throw e.rethrowFromSystemServer();
823 }
Benedict Wong8231eaf2017-12-03 19:42:36 -0800824 }
825
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800826 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700827 * Return number of packets transmitted since device boot. Counts packets
828 * across all network interfaces, and always increases monotonically since
829 * device boot. Statistics are measured at the network layer, so they
830 * include both TCP and UDP usage.
831 * <p>
832 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
833 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800834 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700835 public static long getTotalTxPackets() {
Chenbo Feng65b99192017-11-14 17:54:17 -0800836 try {
837 return getStatsService().getTotalStats(TYPE_TX_PACKETS);
838 } catch (RemoteException e) {
839 throw e.rethrowFromSystemServer();
840 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700841 }
Ken Shirriffae521152009-12-07 15:56:05 -0800842
843 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700844 * Return number of packets received since device boot. Counts packets
845 * across all network interfaces, and always increases monotonically since
846 * device boot. Statistics are measured at the network layer, so they
847 * include both TCP and UDP usage.
848 * <p>
849 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
850 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800851 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700852 public static long getTotalRxPackets() {
Chenbo Feng65b99192017-11-14 17:54:17 -0800853 try {
854 return getStatsService().getTotalStats(TYPE_RX_PACKETS);
855 } catch (RemoteException e) {
856 throw e.rethrowFromSystemServer();
857 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700858 }
Ken Shirriffae521152009-12-07 15:56:05 -0800859
860 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700861 * Return number of bytes transmitted since device boot. Counts packets
862 * across all network interfaces, and always increases monotonically since
863 * device boot. Statistics are measured at the network layer, so they
864 * include both TCP and UDP usage.
865 * <p>
866 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
867 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800868 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700869 public static long getTotalTxBytes() {
Chenbo Feng65b99192017-11-14 17:54:17 -0800870 try {
871 return getStatsService().getTotalStats(TYPE_TX_BYTES);
872 } catch (RemoteException e) {
873 throw e.rethrowFromSystemServer();
874 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700875 }
Ken Shirriffae521152009-12-07 15:56:05 -0800876
877 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700878 * Return number of bytes received since device boot. Counts packets across
879 * all network interfaces, and always increases monotonically since device
880 * boot. Statistics are measured at the network layer, so they include both
881 * TCP and UDP usage.
882 * <p>
883 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
884 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800885 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700886 public static long getTotalRxBytes() {
Chenbo Feng65b99192017-11-14 17:54:17 -0800887 try {
888 return getStatsService().getTotalStats(TYPE_RX_BYTES);
889 } catch (RemoteException e) {
890 throw e.rethrowFromSystemServer();
891 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700892 }
Ken Shirriffae521152009-12-07 15:56:05 -0800893
894 /**
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800895 * Return number of bytes transmitted by the given UID since device boot.
896 * Counts packets across all network interfaces, and always increases
897 * monotonically since device boot. Statistics are measured at the network
898 * layer, so they include both TCP and UDP usage.
899 * <p>
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700900 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
901 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
902 * <p>
903 * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
904 * report traffic statistics for the calling UID. It will return
905 * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
906 * historical network statistics belonging to other UIDs, use
907 * {@link NetworkStatsManager}.
Ken Shirriffae521152009-12-07 15:56:05 -0800908 *
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800909 * @see android.os.Process#myUid()
910 * @see android.content.pm.ApplicationInfo#uid
Ken Shirriffae521152009-12-07 15:56:05 -0800911 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800912 public static long getUidTxBytes(int uid) {
Chenbo Fenge3cff5b2019-06-17 16:22:28 -0700913 try {
914 return getStatsService().getUidStats(uid, TYPE_TX_BYTES);
915 } catch (RemoteException e) {
916 throw e.rethrowFromSystemServer();
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700917 }
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800918 }
Ken Shirriffae521152009-12-07 15:56:05 -0800919
920 /**
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800921 * Return number of bytes received by the given UID since device boot.
922 * Counts packets across all network interfaces, and always increases
923 * monotonically since device boot. Statistics are measured at the network
924 * layer, so they include both TCP and UDP usage.
925 * <p>
Dianne Hackborne9d72072013-02-25 15:55:37 -0800926 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800927 * {@link #UNSUPPORTED} on devices where statistics aren't available.
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700928 * <p>
929 * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
930 * report traffic statistics for the calling UID. It will return
931 * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
932 * historical network statistics belonging to other UIDs, use
933 * {@link NetworkStatsManager}.
Ken Shirriffae521152009-12-07 15:56:05 -0800934 *
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800935 * @see android.os.Process#myUid()
936 * @see android.content.pm.ApplicationInfo#uid
Ken Shirriffae521152009-12-07 15:56:05 -0800937 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800938 public static long getUidRxBytes(int uid) {
Chenbo Fenge3cff5b2019-06-17 16:22:28 -0700939 try {
940 return getStatsService().getUidStats(uid, TYPE_RX_BYTES);
941 } catch (RemoteException e) {
942 throw e.rethrowFromSystemServer();
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700943 }
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800944 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800945
946 /**
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800947 * Return number of packets transmitted by the given UID since device boot.
948 * Counts packets across all network interfaces, and always increases
949 * monotonically since device boot. Statistics are measured at the network
950 * layer, so they include both TCP and UDP usage.
951 * <p>
Dianne Hackborne9d72072013-02-25 15:55:37 -0800952 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800953 * {@link #UNSUPPORTED} on devices where statistics aren't available.
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700954 * <p>
955 * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
956 * report traffic statistics for the calling UID. It will return
957 * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
958 * historical network statistics belonging to other UIDs, use
959 * {@link NetworkStatsManager}.
Ashish Sharmadf852d82011-01-27 15:52:38 -0800960 *
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800961 * @see android.os.Process#myUid()
962 * @see android.content.pm.ApplicationInfo#uid
Ashish Sharmadf852d82011-01-27 15:52:38 -0800963 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800964 public static long getUidTxPackets(int uid) {
Chenbo Fenge3cff5b2019-06-17 16:22:28 -0700965 try {
966 return getStatsService().getUidStats(uid, TYPE_TX_PACKETS);
967 } catch (RemoteException e) {
968 throw e.rethrowFromSystemServer();
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700969 }
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800970 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800971
972 /**
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800973 * Return number of packets received by the given UID since device boot.
974 * Counts packets across all network interfaces, and always increases
975 * monotonically since device boot. Statistics are measured at the network
976 * layer, so they include both TCP and UDP usage.
977 * <p>
Dianne Hackborne9d72072013-02-25 15:55:37 -0800978 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800979 * {@link #UNSUPPORTED} on devices where statistics aren't available.
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700980 * <p>
981 * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
982 * report traffic statistics for the calling UID. It will return
983 * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
984 * historical network statistics belonging to other UIDs, use
985 * {@link NetworkStatsManager}.
Ashish Sharmadf852d82011-01-27 15:52:38 -0800986 *
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800987 * @see android.os.Process#myUid()
988 * @see android.content.pm.ApplicationInfo#uid
Ashish Sharmadf852d82011-01-27 15:52:38 -0800989 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800990 public static long getUidRxPackets(int uid) {
Chenbo Fenge3cff5b2019-06-17 16:22:28 -0700991 try {
992 return getStatsService().getUidStats(uid, TYPE_RX_PACKETS);
993 } catch (RemoteException e) {
994 throw e.rethrowFromSystemServer();
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700995 }
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800996 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800997
998 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -0800999 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001000 * transport layer statistics are no longer available, and will
1001 * always return {@link #UNSUPPORTED}.
1002 * @see #getUidTxBytes(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -08001003 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001004 @Deprecated
1005 public static long getUidTcpTxBytes(int uid) {
1006 return UNSUPPORTED;
1007 }
Ashish Sharmadf852d82011-01-27 15:52:38 -08001008
1009 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -08001010 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001011 * transport layer statistics are no longer available, and will
1012 * always return {@link #UNSUPPORTED}.
1013 * @see #getUidRxBytes(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -08001014 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001015 @Deprecated
1016 public static long getUidTcpRxBytes(int uid) {
1017 return UNSUPPORTED;
1018 }
Ashish Sharmadf852d82011-01-27 15:52:38 -08001019
1020 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -08001021 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001022 * transport layer statistics are no longer available, and will
1023 * always return {@link #UNSUPPORTED}.
1024 * @see #getUidTxBytes(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -08001025 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001026 @Deprecated
1027 public static long getUidUdpTxBytes(int uid) {
1028 return UNSUPPORTED;
1029 }
Ashish Sharmadf852d82011-01-27 15:52:38 -08001030
1031 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -08001032 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001033 * transport layer statistics are no longer available, and will
1034 * always return {@link #UNSUPPORTED}.
1035 * @see #getUidRxBytes(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -08001036 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001037 @Deprecated
1038 public static long getUidUdpRxBytes(int uid) {
1039 return UNSUPPORTED;
1040 }
Ashish Sharmadf852d82011-01-27 15:52:38 -08001041
1042 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -08001043 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001044 * transport layer statistics are no longer available, and will
1045 * always return {@link #UNSUPPORTED}.
1046 * @see #getUidTxPackets(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -08001047 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001048 @Deprecated
1049 public static long getUidTcpTxSegments(int uid) {
1050 return UNSUPPORTED;
1051 }
Ashish Sharmadf852d82011-01-27 15:52:38 -08001052
1053 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -08001054 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001055 * transport layer statistics are no longer available, and will
1056 * always return {@link #UNSUPPORTED}.
1057 * @see #getUidRxPackets(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -08001058 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001059 @Deprecated
1060 public static long getUidTcpRxSegments(int uid) {
1061 return UNSUPPORTED;
1062 }
Ashish Sharmadf852d82011-01-27 15:52:38 -08001063
Ashish Sharmadf852d82011-01-27 15:52:38 -08001064 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -08001065 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001066 * transport layer statistics are no longer available, and will
1067 * always return {@link #UNSUPPORTED}.
1068 * @see #getUidTxPackets(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -08001069 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001070 @Deprecated
1071 public static long getUidUdpTxPackets(int uid) {
1072 return UNSUPPORTED;
1073 }
Ashish Sharmadf852d82011-01-27 15:52:38 -08001074
1075 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -08001076 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001077 * transport layer statistics are no longer available, and will
1078 * always return {@link #UNSUPPORTED}.
1079 * @see #getUidRxPackets(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -08001080 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001081 @Deprecated
1082 public static long getUidUdpRxPackets(int uid) {
1083 return UNSUPPORTED;
1084 }
Jeff Sharkey33936ac2011-05-17 14:55:15 -07001085
1086 /**
1087 * Return detailed {@link NetworkStats} for the current UID. Requires no
1088 * special permission.
1089 */
Jeff Sharkey7407e092011-07-19 23:47:12 -07001090 private static NetworkStats getDataLayerSnapshotForUid(Context context) {
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -07001091 // TODO: take snapshot locally, since proc file is now visible
Jeff Sharkey33936ac2011-05-17 14:55:15 -07001092 final int uid = android.os.Process.myUid();
1093 try {
Jeff Sharkey8308b9b2012-04-10 19:48:07 -07001094 return getStatsService().getDataLayerSnapshotForUid(uid);
Jeff Sharkey33936ac2011-05-17 14:55:15 -07001095 } catch (RemoteException e) {
Jeff Sharkeybc08d072016-02-26 13:03:01 -07001096 throw e.rethrowFromSystemServer();
Jeff Sharkey33936ac2011-05-17 14:55:15 -07001097 }
1098 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -07001099
1100 /**
1101 * Return set of any ifaces associated with mobile networks since boot.
1102 * Interfaces are never removed from this list, so counters should always be
1103 * monotonic.
1104 */
Chalard Jean4722cf12019-04-09 15:46:21 +09001105 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey8308b9b2012-04-10 19:48:07 -07001106 private static String[] getMobileIfaces() {
1107 try {
1108 return getStatsService().getMobileIfaces();
1109 } catch (RemoteException e) {
Jeff Sharkeybc08d072016-02-26 13:03:01 -07001110 throw e.rethrowFromSystemServer();
Jeff Sharkey8308b9b2012-04-10 19:48:07 -07001111 }
1112 }
1113
junyulai3841fbe2020-10-06 11:59:56 +08001114 // NOTE: keep these in sync with {@code com_android_server_net_NetworkStatsService.cpp}.
1115 /** {@hide} */
1116 public static final int TYPE_RX_BYTES = 0;
1117 /** {@hide} */
1118 public static final int TYPE_RX_PACKETS = 1;
1119 /** {@hide} */
1120 public static final int TYPE_TX_BYTES = 2;
1121 /** {@hide} */
1122 public static final int TYPE_TX_PACKETS = 3;
Ken Shirriffae521152009-12-07 15:56:05 -08001123}