blob: e408cbb42224b25f994da3fbd8806f36078a5bb3 [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() {
685 long total = 0;
686 for (String iface : getMobileIfaces()) {
Chenbo Feng65b99192017-11-14 17:54:17 -0800687 long stat = UNSUPPORTED;
688 try {
689 stat = getStatsService().getIfaceStats(iface, TYPE_TCP_RX_PACKETS);
690 } catch (RemoteException e) {
691 throw e.rethrowFromSystemServer();
692 }
Chenbo Feng7f880c92018-01-25 11:43:52 -0800693 total += addIfSupported(stat);
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800694 }
695 return total;
696 }
697
698 /** {@hide} */
Mathew Inwood5c74a0f2020-11-04 09:29:36 +0000699 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800700 public static long getMobileTcpTxPackets() {
701 long total = 0;
702 for (String iface : getMobileIfaces()) {
Chenbo Feng65b99192017-11-14 17:54:17 -0800703 long stat = UNSUPPORTED;
704 try {
705 stat = getStatsService().getIfaceStats(iface, TYPE_TCP_TX_PACKETS);
706 } catch (RemoteException e) {
707 throw e.rethrowFromSystemServer();
708 }
Chenbo Feng7f880c92018-01-25 11:43:52 -0800709 total += addIfSupported(stat);
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800710 }
711 return total;
712 }
713
Aaron Huangb0db4fd2019-09-27 22:31:22 +0800714 /**
junyulai01f60b22020-09-29 14:19:24 +0800715 * Return the number of packets transmitted on the specified interface since the interface
716 * was created. Statistics are measured at the network layer, so both TCP and
Aaron Huangb0db4fd2019-09-27 22:31:22 +0800717 * UDP usage are included.
718 *
junyulai01f60b22020-09-29 14:19:24 +0800719 * Note that the returned values are partial statistics that do not count data from several
720 * sources and do not apply several adjustments that are necessary for correctness, such
721 * as adjusting for VPN apps, IPv6-in-IPv4 translation, etc. These values can be used to
722 * determine whether traffic is being transferred on the specific interface but are not a
723 * substitute for the more accurate statistics provided by the {@link NetworkStatsManager}
724 * APIs.
725 *
Aaron Huangb0db4fd2019-09-27 22:31:22 +0800726 * @param iface The name of the interface.
727 * @return The number of transmitted packets.
728 */
729 public static long getTxPackets(@NonNull String iface) {
Chenbo Feng65b99192017-11-14 17:54:17 -0800730 try {
731 return getStatsService().getIfaceStats(iface, TYPE_TX_PACKETS);
732 } catch (RemoteException e) {
733 throw e.rethrowFromSystemServer();
734 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700735 }
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800736
Aaron Huangb0db4fd2019-09-27 22:31:22 +0800737 /**
junyulai01f60b22020-09-29 14:19:24 +0800738 * Return the number of packets received on the specified interface since the interface was
739 * created. Statistics are measured at the network layer, so both TCP
Aaron Huangb0db4fd2019-09-27 22:31:22 +0800740 * and UDP usage are included.
741 *
junyulai01f60b22020-09-29 14:19:24 +0800742 * Note that the returned values are partial statistics that do not count data from several
743 * sources and do not apply several adjustments that are necessary for correctness, such
744 * as adjusting for VPN apps, IPv6-in-IPv4 translation, etc. These values can be used to
745 * determine whether traffic is being transferred on the specific interface but are not a
746 * substitute for the more accurate statistics provided by the {@link NetworkStatsManager}
747 * APIs.
748 *
Aaron Huangb0db4fd2019-09-27 22:31:22 +0800749 * @param iface The name of the interface.
750 * @return The number of received packets.
751 */
752 public static long getRxPackets(@NonNull String iface) {
Chenbo Feng65b99192017-11-14 17:54:17 -0800753 try {
754 return getStatsService().getIfaceStats(iface, TYPE_RX_PACKETS);
755 } catch (RemoteException e) {
756 throw e.rethrowFromSystemServer();
757 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700758 }
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800759
junyulai01f60b22020-09-29 14:19:24 +0800760 /**
761 * Return the number of bytes transmitted on the specified interface since the interface
762 * was created. Statistics are measured at the network layer, so both TCP and
763 * UDP usage are included.
764 *
765 * Note that the returned values are partial statistics that do not count data from several
766 * sources and do not apply several adjustments that are necessary for correctness, such
767 * as adjusting for VPN apps, IPv6-in-IPv4 translation, etc. These values can be used to
768 * determine whether traffic is being transferred on the specific interface but are not a
769 * substitute for the more accurate statistics provided by the {@link NetworkStatsManager}
770 * APIs.
771 *
772 * @param iface The name of the interface.
773 * @return The number of transmitted bytes.
774 */
775 public static long getTxBytes(@NonNull String iface) {
Chenbo Feng65b99192017-11-14 17:54:17 -0800776 try {
777 return getStatsService().getIfaceStats(iface, TYPE_TX_BYTES);
778 } catch (RemoteException e) {
779 throw e.rethrowFromSystemServer();
780 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700781 }
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800782
junyulai01f60b22020-09-29 14:19:24 +0800783 /**
784 * Return the number of bytes received on the specified interface since the interface
785 * was created. Statistics are measured at the network layer, so both TCP
786 * and UDP usage are included.
787 *
788 * Note that the returned values are partial statistics that do not count data from several
789 * sources and do not apply several adjustments that are necessary for correctness, such
790 * as adjusting for VPN apps, IPv6-in-IPv4 translation, etc. These values can be used to
791 * determine whether traffic is being transferred on the specific interface but are not a
792 * substitute for the more accurate statistics provided by the {@link NetworkStatsManager}
793 * APIs.
794 *
795 * @param iface The name of the interface.
796 * @return The number of received bytes.
797 */
798 public static long getRxBytes(@NonNull String iface) {
Chenbo Feng65b99192017-11-14 17:54:17 -0800799 try {
800 return getStatsService().getIfaceStats(iface, TYPE_RX_BYTES);
801 } catch (RemoteException e) {
802 throw e.rethrowFromSystemServer();
803 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700804 }
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800805
Benedict Wong8231eaf2017-12-03 19:42:36 -0800806 /** {@hide} */
807 @TestApi
808 public static long getLoopbackTxPackets() {
Chenbo Feng65b99192017-11-14 17:54:17 -0800809 try {
810 return getStatsService().getIfaceStats(LOOPBACK_IFACE, TYPE_TX_PACKETS);
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 getLoopbackRxPackets() {
Chenbo Feng65b99192017-11-14 17:54:17 -0800819 try {
820 return getStatsService().getIfaceStats(LOOPBACK_IFACE, TYPE_RX_PACKETS);
821 } catch (RemoteException e) {
822 throw e.rethrowFromSystemServer();
823 }
Benedict Wong8231eaf2017-12-03 19:42:36 -0800824 }
825
826 /** {@hide} */
827 @TestApi
828 public static long getLoopbackTxBytes() {
Chenbo Feng65b99192017-11-14 17:54:17 -0800829 try {
830 return getStatsService().getIfaceStats(LOOPBACK_IFACE, TYPE_TX_BYTES);
831 } catch (RemoteException e) {
832 throw e.rethrowFromSystemServer();
833 }
Benedict Wong8231eaf2017-12-03 19:42:36 -0800834 }
835
836 /** {@hide} */
837 @TestApi
838 public static long getLoopbackRxBytes() {
Chenbo Feng65b99192017-11-14 17:54:17 -0800839 try {
840 return getStatsService().getIfaceStats(LOOPBACK_IFACE, TYPE_RX_BYTES);
841 } catch (RemoteException e) {
842 throw e.rethrowFromSystemServer();
843 }
Benedict Wong8231eaf2017-12-03 19:42:36 -0800844 }
845
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800846 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700847 * Return number of packets transmitted since device boot. Counts packets
848 * across all network interfaces, and always increases monotonically since
849 * device boot. Statistics are measured at the network layer, so they
850 * include both TCP and UDP usage.
851 * <p>
852 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
853 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800854 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700855 public static long getTotalTxPackets() {
Chenbo Feng65b99192017-11-14 17:54:17 -0800856 try {
857 return getStatsService().getTotalStats(TYPE_TX_PACKETS);
858 } catch (RemoteException e) {
859 throw e.rethrowFromSystemServer();
860 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700861 }
Ken Shirriffae521152009-12-07 15:56:05 -0800862
863 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700864 * Return number of packets received since device boot. Counts packets
865 * across all network interfaces, and always increases monotonically since
866 * device boot. Statistics are measured at the network layer, so they
867 * include both TCP and UDP usage.
868 * <p>
869 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
870 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800871 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700872 public static long getTotalRxPackets() {
Chenbo Feng65b99192017-11-14 17:54:17 -0800873 try {
874 return getStatsService().getTotalStats(TYPE_RX_PACKETS);
875 } catch (RemoteException e) {
876 throw e.rethrowFromSystemServer();
877 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700878 }
Ken Shirriffae521152009-12-07 15:56:05 -0800879
880 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700881 * Return number of bytes transmitted since device boot. Counts packets
882 * across all network interfaces, and always increases monotonically since
883 * device boot. Statistics are measured at the network layer, so they
884 * include both TCP and UDP usage.
885 * <p>
886 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
887 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800888 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700889 public static long getTotalTxBytes() {
Chenbo Feng65b99192017-11-14 17:54:17 -0800890 try {
891 return getStatsService().getTotalStats(TYPE_TX_BYTES);
892 } catch (RemoteException e) {
893 throw e.rethrowFromSystemServer();
894 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700895 }
Ken Shirriffae521152009-12-07 15:56:05 -0800896
897 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700898 * Return number of bytes received since device boot. Counts packets across
899 * all network interfaces, and always increases monotonically since device
900 * boot. Statistics are measured at the network layer, so they include both
901 * TCP and UDP usage.
902 * <p>
903 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
904 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800905 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700906 public static long getTotalRxBytes() {
Chenbo Feng65b99192017-11-14 17:54:17 -0800907 try {
908 return getStatsService().getTotalStats(TYPE_RX_BYTES);
909 } catch (RemoteException e) {
910 throw e.rethrowFromSystemServer();
911 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700912 }
Ken Shirriffae521152009-12-07 15:56:05 -0800913
914 /**
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800915 * Return number of bytes transmitted by the given UID since device boot.
916 * Counts packets across all network interfaces, and always increases
917 * monotonically since device boot. Statistics are measured at the network
918 * layer, so they include both TCP and UDP usage.
919 * <p>
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700920 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
921 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
922 * <p>
923 * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
924 * report traffic statistics for the calling UID. It will return
925 * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
926 * historical network statistics belonging to other UIDs, use
927 * {@link NetworkStatsManager}.
Ken Shirriffae521152009-12-07 15:56:05 -0800928 *
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800929 * @see android.os.Process#myUid()
930 * @see android.content.pm.ApplicationInfo#uid
Ken Shirriffae521152009-12-07 15:56:05 -0800931 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800932 public static long getUidTxBytes(int uid) {
Chenbo Fenge3cff5b2019-06-17 16:22:28 -0700933 try {
934 return getStatsService().getUidStats(uid, TYPE_TX_BYTES);
935 } catch (RemoteException e) {
936 throw e.rethrowFromSystemServer();
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700937 }
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800938 }
Ken Shirriffae521152009-12-07 15:56:05 -0800939
940 /**
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800941 * Return number of bytes received by the given UID since device boot.
942 * Counts packets across all network interfaces, and always increases
943 * monotonically since device boot. Statistics are measured at the network
944 * layer, so they include both TCP and UDP usage.
945 * <p>
Dianne Hackborne9d72072013-02-25 15:55:37 -0800946 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800947 * {@link #UNSUPPORTED} on devices where statistics aren't available.
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700948 * <p>
949 * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
950 * report traffic statistics for the calling UID. It will return
951 * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
952 * historical network statistics belonging to other UIDs, use
953 * {@link NetworkStatsManager}.
Ken Shirriffae521152009-12-07 15:56:05 -0800954 *
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800955 * @see android.os.Process#myUid()
956 * @see android.content.pm.ApplicationInfo#uid
Ken Shirriffae521152009-12-07 15:56:05 -0800957 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800958 public static long getUidRxBytes(int uid) {
Chenbo Fenge3cff5b2019-06-17 16:22:28 -0700959 try {
960 return getStatsService().getUidStats(uid, TYPE_RX_BYTES);
961 } catch (RemoteException e) {
962 throw e.rethrowFromSystemServer();
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700963 }
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800964 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800965
966 /**
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800967 * Return number of packets transmitted by the given UID since device boot.
968 * Counts packets across all network interfaces, and always increases
969 * monotonically since device boot. Statistics are measured at the network
970 * layer, so they include both TCP and UDP usage.
971 * <p>
Dianne Hackborne9d72072013-02-25 15:55:37 -0800972 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800973 * {@link #UNSUPPORTED} on devices where statistics aren't available.
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700974 * <p>
975 * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
976 * report traffic statistics for the calling UID. It will return
977 * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
978 * historical network statistics belonging to other UIDs, use
979 * {@link NetworkStatsManager}.
Ashish Sharmadf852d82011-01-27 15:52:38 -0800980 *
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800981 * @see android.os.Process#myUid()
982 * @see android.content.pm.ApplicationInfo#uid
Ashish Sharmadf852d82011-01-27 15:52:38 -0800983 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800984 public static long getUidTxPackets(int uid) {
Chenbo Fenge3cff5b2019-06-17 16:22:28 -0700985 try {
986 return getStatsService().getUidStats(uid, TYPE_TX_PACKETS);
987 } catch (RemoteException e) {
988 throw e.rethrowFromSystemServer();
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700989 }
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800990 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800991
992 /**
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800993 * Return number of packets received by the given UID since device boot.
994 * Counts packets across all network interfaces, and always increases
995 * monotonically since device boot. Statistics are measured at the network
996 * layer, so they include both TCP and UDP usage.
997 * <p>
Dianne Hackborne9d72072013-02-25 15:55:37 -0800998 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800999 * {@link #UNSUPPORTED} on devices where statistics aren't available.
Jeff Sharkey27c8a072016-03-09 16:40:15 -07001000 * <p>
1001 * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
1002 * report traffic statistics for the calling UID. It will return
1003 * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
1004 * historical network statistics belonging to other UIDs, use
1005 * {@link NetworkStatsManager}.
Ashish Sharmadf852d82011-01-27 15:52:38 -08001006 *
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001007 * @see android.os.Process#myUid()
1008 * @see android.content.pm.ApplicationInfo#uid
Ashish Sharmadf852d82011-01-27 15:52:38 -08001009 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001010 public static long getUidRxPackets(int uid) {
Chenbo Fenge3cff5b2019-06-17 16:22:28 -07001011 try {
1012 return getStatsService().getUidStats(uid, TYPE_RX_PACKETS);
1013 } catch (RemoteException e) {
1014 throw e.rethrowFromSystemServer();
Jeff Sharkey27c8a072016-03-09 16:40:15 -07001015 }
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001016 }
Ashish Sharmadf852d82011-01-27 15:52:38 -08001017
1018 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -08001019 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001020 * transport layer statistics are no longer available, and will
1021 * always return {@link #UNSUPPORTED}.
1022 * @see #getUidTxBytes(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -08001023 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001024 @Deprecated
1025 public static long getUidTcpTxBytes(int uid) {
1026 return UNSUPPORTED;
1027 }
Ashish Sharmadf852d82011-01-27 15:52:38 -08001028
1029 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -08001030 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001031 * transport layer statistics are no longer available, and will
1032 * always return {@link #UNSUPPORTED}.
1033 * @see #getUidRxBytes(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -08001034 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001035 @Deprecated
1036 public static long getUidTcpRxBytes(int uid) {
1037 return UNSUPPORTED;
1038 }
Ashish Sharmadf852d82011-01-27 15:52:38 -08001039
1040 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -08001041 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001042 * transport layer statistics are no longer available, and will
1043 * always return {@link #UNSUPPORTED}.
1044 * @see #getUidTxBytes(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -08001045 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001046 @Deprecated
1047 public static long getUidUdpTxBytes(int uid) {
1048 return UNSUPPORTED;
1049 }
Ashish Sharmadf852d82011-01-27 15:52:38 -08001050
1051 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -08001052 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001053 * transport layer statistics are no longer available, and will
1054 * always return {@link #UNSUPPORTED}.
1055 * @see #getUidRxBytes(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -08001056 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001057 @Deprecated
1058 public static long getUidUdpRxBytes(int uid) {
1059 return UNSUPPORTED;
1060 }
Ashish Sharmadf852d82011-01-27 15:52:38 -08001061
1062 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -08001063 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001064 * transport layer statistics are no longer available, and will
1065 * always return {@link #UNSUPPORTED}.
1066 * @see #getUidTxPackets(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -08001067 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001068 @Deprecated
1069 public static long getUidTcpTxSegments(int uid) {
1070 return UNSUPPORTED;
1071 }
Ashish Sharmadf852d82011-01-27 15:52:38 -08001072
1073 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -08001074 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001075 * transport layer statistics are no longer available, and will
1076 * always return {@link #UNSUPPORTED}.
1077 * @see #getUidRxPackets(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -08001078 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001079 @Deprecated
1080 public static long getUidTcpRxSegments(int uid) {
1081 return UNSUPPORTED;
1082 }
Ashish Sharmadf852d82011-01-27 15:52:38 -08001083
Ashish Sharmadf852d82011-01-27 15:52:38 -08001084 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -08001085 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001086 * transport layer statistics are no longer available, and will
1087 * always return {@link #UNSUPPORTED}.
1088 * @see #getUidTxPackets(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -08001089 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001090 @Deprecated
1091 public static long getUidUdpTxPackets(int uid) {
1092 return UNSUPPORTED;
1093 }
Ashish Sharmadf852d82011-01-27 15:52:38 -08001094
1095 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -08001096 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001097 * transport layer statistics are no longer available, and will
1098 * always return {@link #UNSUPPORTED}.
1099 * @see #getUidRxPackets(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -08001100 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001101 @Deprecated
1102 public static long getUidUdpRxPackets(int uid) {
1103 return UNSUPPORTED;
1104 }
Jeff Sharkey33936ac2011-05-17 14:55:15 -07001105
1106 /**
1107 * Return detailed {@link NetworkStats} for the current UID. Requires no
1108 * special permission.
1109 */
Jeff Sharkey7407e092011-07-19 23:47:12 -07001110 private static NetworkStats getDataLayerSnapshotForUid(Context context) {
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -07001111 // TODO: take snapshot locally, since proc file is now visible
Jeff Sharkey33936ac2011-05-17 14:55:15 -07001112 final int uid = android.os.Process.myUid();
1113 try {
Jeff Sharkey8308b9b2012-04-10 19:48:07 -07001114 return getStatsService().getDataLayerSnapshotForUid(uid);
Jeff Sharkey33936ac2011-05-17 14:55:15 -07001115 } catch (RemoteException e) {
Jeff Sharkeybc08d072016-02-26 13:03:01 -07001116 throw e.rethrowFromSystemServer();
Jeff Sharkey33936ac2011-05-17 14:55:15 -07001117 }
1118 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -07001119
1120 /**
1121 * Return set of any ifaces associated with mobile networks since boot.
1122 * Interfaces are never removed from this list, so counters should always be
1123 * monotonic.
1124 */
Chalard Jean4722cf12019-04-09 15:46:21 +09001125 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey8308b9b2012-04-10 19:48:07 -07001126 private static String[] getMobileIfaces() {
1127 try {
1128 return getStatsService().getMobileIfaces();
1129 } catch (RemoteException e) {
Jeff Sharkeybc08d072016-02-26 13:03:01 -07001130 throw e.rethrowFromSystemServer();
Jeff Sharkey8308b9b2012-04-10 19:48:07 -07001131 }
1132 }
1133
junyulai3841fbe2020-10-06 11:59:56 +08001134 // NOTE: keep these in sync with {@code com_android_server_net_NetworkStatsService.cpp}.
1135 /** {@hide} */
1136 public static final int TYPE_RX_BYTES = 0;
1137 /** {@hide} */
1138 public static final int TYPE_RX_PACKETS = 1;
1139 /** {@hide} */
1140 public static final int TYPE_TX_BYTES = 2;
1141 /** {@hide} */
1142 public static final int TYPE_TX_PACKETS = 3;
1143 /** {@hide} */
1144 public static final int TYPE_TCP_RX_PACKETS = 4;
1145 /** {@hide} */
1146 public static final int TYPE_TCP_TX_PACKETS = 5;
Ken Shirriffae521152009-12-07 15:56:05 -08001147}