blob: bc836d857e3ec4e5dff589123ce110a1bbb74b5f [file] [log] [blame]
Ken Shirriffae521152009-12-07 15:56:05 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.net;
18
Junyu Lai8e58c822022-01-17 17:05:30 +000019import static android.annotation.SystemApi.Client.MODULE_LIBRARIES;
20
Aaron Huang443651d2019-09-27 22:31:22 +080021import android.annotation.NonNull;
Jeff Sharkey1fb74312017-11-29 11:18:23 -070022import android.annotation.SuppressLint;
Christopher Tate5a1878d2014-08-06 14:19:56 -070023import android.annotation.SystemApi;
Benedict Wong083faee2017-12-03 19:42:36 -080024import android.annotation.TestApi;
Jeff Sharkey92790062011-06-24 17:05:24 -070025import android.app.DownloadManager;
26import android.app.backup.BackupManager;
Jeff Sharkey27c8a072016-03-09 16:40:15 -070027import android.app.usage.NetworkStatsManager;
Artur Satayev164c7562019-12-10 17:47:52 +000028import android.compat.annotation.UnsupportedAppUsage;
Jeff Sharkey33936ac2011-05-17 14:55:15 -070029import android.content.Context;
Jeff Sharkey92790062011-06-24 17:05:24 -070030import android.media.MediaPlayer;
Junyu Lai92d5b4c2022-01-19 08:33:21 +000031import android.os.Binder;
Chalard Jean3cfb4992019-04-09 15:46:21 +090032import android.os.Build;
Jeff Sharkey33936ac2011-05-17 14:55:15 -070033import android.os.RemoteException;
Lorenzo Colittid2ae7392022-01-29 21:07:33 +090034import android.os.StrictMode;
Junyu Lai3355c402022-01-25 07:40:06 +000035import android.util.Log;
Jeff Sharkey33936ac2011-05-17 14:55:15 -070036
Jeff Sharkey1fb74312017-11-29 11:18:23 -070037import java.io.FileDescriptor;
38import java.io.IOException;
Jeff Sharkey7b124cb2015-12-04 15:21:52 -070039import java.net.DatagramSocket;
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -070040import java.net.Socket;
41import java.net.SocketException;
Ken Shirriffae521152009-12-07 15:56:05 -080042
43/**
Jeff Sharkey27c8a072016-03-09 16:40:15 -070044 * Class that provides network traffic statistics. These statistics include
Dan Egnoreaeb7022010-04-07 17:30:50 -070045 * bytes transmitted and received and network packets transmitted and received,
46 * over all interfaces, over the mobile interface, and on a per-UID basis.
Ken Shirriffae521152009-12-07 15:56:05 -080047 * <p>
Jeff Sharkey27c8a072016-03-09 16:40:15 -070048 * These statistics may not be available on all platforms. If the statistics are
49 * not supported by this device, {@link #UNSUPPORTED} will be returned.
50 * <p>
51 * Note that the statistics returned by this class reset and start from zero
52 * after every reboot. To access more robust historical network statistics data,
53 * use {@link NetworkStatsManager} instead.
Ken Shirriffae521152009-12-07 15:56:05 -080054 */
55public class TrafficStats {
Lorenzo Colittid2ae7392022-01-29 21:07:33 +090056 static {
57 System.loadLibrary("framework-connectivity-tiramisu-jni");
58 }
59
Junyu Lai3f7bb332021-12-28 16:18:43 +000060 private static final String TAG = TrafficStats.class.getSimpleName();
Ken Shirriffae521152009-12-07 15:56:05 -080061 /**
62 * The return value to indicate that the device does not support the statistic.
63 */
64 public final static int UNSUPPORTED = -1;
65
Junyu Lai1d3ce852021-12-27 13:56:59 +000066 /** @hide @deprecated use {@code DataUnit} instead to clarify SI-vs-IEC */
Jeff Sharkeya6886af2018-01-07 16:47:31 -070067 @Deprecated
Jeff Sharkey94a315c2012-02-03 14:50:07 -080068 public static final long KB_IN_BYTES = 1024;
Junyu Lai1d3ce852021-12-27 13:56:59 +000069 /** @hide @deprecated use {@code DataUnit} instead to clarify SI-vs-IEC */
Jeff Sharkeya6886af2018-01-07 16:47:31 -070070 @Deprecated
Jeff Sharkey94a315c2012-02-03 14:50:07 -080071 public static final long MB_IN_BYTES = KB_IN_BYTES * 1024;
Junyu Lai1d3ce852021-12-27 13:56:59 +000072 /** @hide @deprecated use {@code DataUnit} instead to clarify SI-vs-IEC */
Jeff Sharkeya6886af2018-01-07 16:47:31 -070073 @Deprecated
Jeff Sharkey94a315c2012-02-03 14:50:07 -080074 public static final long GB_IN_BYTES = MB_IN_BYTES * 1024;
Junyu Lai1d3ce852021-12-27 13:56:59 +000075 /** @hide @deprecated use {@code DataUnit} instead to clarify SI-vs-IEC */
Jeff Sharkeya6886af2018-01-07 16:47:31 -070076 @Deprecated
Jeff Sharkey6f2ba5e2015-03-18 11:27:19 -070077 public static final long TB_IN_BYTES = GB_IN_BYTES * 1024;
Junyu Lai1d3ce852021-12-27 13:56:59 +000078 /** @hide @deprecated use {@code DataUnit} instead to clarify SI-vs-IEC */
Jeff Sharkeya6886af2018-01-07 16:47:31 -070079 @Deprecated
Jeff Sharkey88069072015-06-15 21:09:10 -070080 public static final long PB_IN_BYTES = TB_IN_BYTES * 1024;
Jeff Sharkey94a315c2012-02-03 14:50:07 -080081
Jeff Sharkey1a3eb882011-05-28 20:56:34 -070082 /**
Jeff Sharkeyc04cda62011-06-19 01:08:12 -070083 * Special UID value used when collecting {@link NetworkStatsHistory} for
84 * removed applications.
85 *
86 * @hide
87 */
88 public static final int UID_REMOVED = -4;
89
90 /**
Jeff Sharkey987f5ff2011-09-16 01:52:49 -070091 * Special UID value used when collecting {@link NetworkStatsHistory} for
92 * tethering traffic.
93 *
94 * @hide
95 */
junyulai55041a42019-11-15 17:15:01 +080096 public static final int UID_TETHERING = NetworkStats.UID_TETHERING;
Jeff Sharkey987f5ff2011-09-16 01:52:49 -070097
98 /**
Chalard Jean8a93ab82019-04-09 11:16:56 +090099 * Tag values in this range are reserved for the network stack. The network stack is
100 * running as UID {@link android.os.Process.NETWORK_STACK_UID} when in the mainline
101 * module separate process, and as the system UID otherwise.
102 */
103 /** @hide */
104 @SystemApi
105 public static final int TAG_NETWORK_STACK_RANGE_START = 0xFFFFFD00;
106 /** @hide */
107 @SystemApi
108 public static final int TAG_NETWORK_STACK_RANGE_END = 0xFFFFFEFF;
109
110 /**
111 * Tags between 0xFFFFFF00 and 0xFFFFFFFF are reserved and used internally by system services
112 * like DownloadManager when performing traffic on behalf of an application.
113 */
114 // Please note there is no enforcement of these constants, so do not rely on them to
115 // determine that the caller is a system caller.
116 /** @hide */
117 @SystemApi
118 public static final int TAG_SYSTEM_IMPERSONATION_RANGE_START = 0xFFFFFF00;
119 /** @hide */
120 @SystemApi
121 public static final int TAG_SYSTEM_IMPERSONATION_RANGE_END = 0xFFFFFF0F;
122
123 /**
124 * Tag values between these ranges are reserved for the network stack to do traffic
125 * on behalf of applications. It is a subrange of the range above.
126 */
127 /** @hide */
128 @SystemApi
129 public static final int TAG_NETWORK_STACK_IMPERSONATION_RANGE_START = 0xFFFFFF80;
130 /** @hide */
131 @SystemApi
132 public static final int TAG_NETWORK_STACK_IMPERSONATION_RANGE_END = 0xFFFFFF8F;
133
134 /**
Jeff Sharkey92790062011-06-24 17:05:24 -0700135 * Default tag value for {@link DownloadManager} traffic.
136 *
137 * @hide
138 */
Jeff Sharkey987f5ff2011-09-16 01:52:49 -0700139 public static final int TAG_SYSTEM_DOWNLOAD = 0xFFFFFF01;
Jeff Sharkey92790062011-06-24 17:05:24 -0700140
141 /**
142 * Default tag value for {@link MediaPlayer} traffic.
143 *
144 * @hide
145 */
Jeff Sharkey987f5ff2011-09-16 01:52:49 -0700146 public static final int TAG_SYSTEM_MEDIA = 0xFFFFFF02;
Jeff Sharkey92790062011-06-24 17:05:24 -0700147
148 /**
Christopher Tatec1c71fd2015-11-10 10:49:20 -0800149 * Default tag value for {@link BackupManager} backup traffic; that is,
150 * traffic from the device to the storage backend.
Jeff Sharkey92790062011-06-24 17:05:24 -0700151 *
152 * @hide
153 */
Jeff Sharkey987f5ff2011-09-16 01:52:49 -0700154 public static final int TAG_SYSTEM_BACKUP = 0xFFFFFF03;
Jeff Sharkey92790062011-06-24 17:05:24 -0700155
Christopher Tatec1c71fd2015-11-10 10:49:20 -0800156 /**
157 * Default tag value for {@link BackupManager} restore traffic; that is,
158 * app data retrieved from the storage backend at install time.
159 *
160 * @hide
161 */
162 public static final int TAG_SYSTEM_RESTORE = 0xFFFFFF04;
163
Jeff Sharkey66dca172016-11-21 12:14:50 -0700164 /**
Jeff Sharkeyb1f97ac2017-08-11 15:04:12 -0600165 * Default tag value for code (typically APKs) downloaded by an app store on
166 * behalf of the app, such as updates.
Jeff Sharkey66dca172016-11-21 12:14:50 -0700167 *
168 * @hide
169 */
Jeff Sharkeyb1f97ac2017-08-11 15:04:12 -0600170 public static final int TAG_SYSTEM_APP = 0xFFFFFF05;
Jeff Sharkey8af5ad12017-06-26 19:50:41 -0600171
Chalard Jean8a93ab82019-04-09 11:16:56 +0900172 // TODO : remove this constant when Wifi code is updated
Jeff Sharkey8af5ad12017-06-26 19:50:41 -0600173 /** @hide */
Jeff Sharkey8af5ad12017-06-26 19:50:41 -0600174 public static final int TAG_SYSTEM_PROBE = 0xFFFFFF42;
Jeff Sharkey66dca172016-11-21 12:14:50 -0700175
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700176 private static INetworkStatsService sStatsService;
177
Chalard Jean3cfb4992019-04-09 15:46:21 +0900178 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700179 private synchronized static INetworkStatsService getStatsService() {
180 if (sStatsService == null) {
Junyu Lai92d5b4c2022-01-19 08:33:21 +0000181 throw new IllegalStateException("TrafficStats not initialized, uid="
182 + Binder.getCallingUid());
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700183 }
184 return sStatsService;
185 }
186
Jeff Sharkey92790062011-06-24 17:05:24 -0700187 /**
Jeff Sharkey33936ac2011-05-17 14:55:15 -0700188 * Snapshot of {@link NetworkStats} when the currently active profiling
189 * session started, or {@code null} if no session active.
190 *
191 * @see #startDataProfiling(Context)
192 * @see #stopDataProfiling(Context)
193 */
194 private static NetworkStats sActiveProfilingStart;
195
196 private static Object sProfilingLock = new Object();
197
Benedict Wong083faee2017-12-03 19:42:36 -0800198 private static final String LOOPBACK_IFACE = "lo";
199
Jeff Sharkey33936ac2011-05-17 14:55:15 -0700200 /**
Junyu Lai92d5b4c2022-01-19 08:33:21 +0000201 * Initialization {@link TrafficStats} with the context, to
202 * allow {@link TrafficStats} to fetch the needed binder.
203 *
204 * @param context a long-lived context, such as the application context or system
205 * server context.
206 * @hide
207 */
208 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
209 @SuppressLint("VisiblySynchronized")
210 public static synchronized void init(@NonNull final Context context) {
211 if (sStatsService != null) {
212 throw new IllegalStateException("TrafficStats is already initialized, uid="
213 + Binder.getCallingUid());
214 }
215 final NetworkStatsManager statsManager =
216 context.getSystemService(NetworkStatsManager.class);
Junyu Lai3355c402022-01-25 07:40:06 +0000217 if (statsManager == null) {
218 // TODO: Currently Process.isSupplemental is not working yet, because it depends on
219 // process to run in a certain UID range, which is not true for now. Change this
220 // to Log.wtf once Process.isSupplemental is ready.
221 Log.e(TAG, "TrafficStats not initialized, uid=" + Binder.getCallingUid());
222 return;
223 }
Junyu Lai92d5b4c2022-01-19 08:33:21 +0000224 sStatsService = statsManager.getBinder();
225 }
226
227 /**
Junyu Lai8e58c822022-01-17 17:05:30 +0000228 * Attach the socket tagger implementation to the current process, to
229 * get notified when a socket's {@link FileDescriptor} is assigned to
230 * a thread. See {@link SocketTagger#set(SocketTagger)}.
231 *
232 * @hide
233 */
234 @SystemApi(client = MODULE_LIBRARIES)
235 public static void attachSocketTagger() {
Lorenzo Colittid2ae7392022-01-29 21:07:33 +0900236 dalvik.system.SocketTagger.set(new SocketTagger());
Junyu Lai8e58c822022-01-17 17:05:30 +0000237 }
238
Lorenzo Colittid2ae7392022-01-29 21:07:33 +0900239 private static class SocketTagger extends dalvik.system.SocketTagger {
240
241 // TODO: set to false
242 private static final boolean LOGD = true;
243
244 SocketTagger() {
245 }
246
247 @Override
248 public void tag(FileDescriptor fd) throws SocketException {
249 final UidTag tagInfo = sThreadUidTag.get();
250 if (LOGD) {
251 Log.d(TAG, "tagSocket(" + fd.getInt$() + ") with statsTag=0x"
252 + Integer.toHexString(tagInfo.tag) + ", statsUid=" + tagInfo.uid);
253 }
254 if (tagInfo.tag == -1) {
255 StrictMode.noteUntaggedSocket();
256 }
257
258 if (tagInfo.tag == -1 && tagInfo.uid == -1) return;
259 final int errno = native_tagSocketFd(fd, tagInfo.tag, tagInfo.uid);
260 if (errno < 0) {
261 Log.i(TAG, "tagSocketFd(" + fd.getInt$() + ", "
262 + tagInfo.tag + ", "
263 + tagInfo.uid + ") failed with errno" + errno);
264 }
265 }
266
267 @Override
268 public void untag(FileDescriptor fd) throws SocketException {
269 if (LOGD) {
270 Log.i(TAG, "untagSocket(" + fd.getInt$() + ")");
271 }
272
273 final UidTag tagInfo = sThreadUidTag.get();
274 if (tagInfo.tag == -1 && tagInfo.uid == -1) return;
275
276 final int errno = native_untagSocketFd(fd);
277 if (errno < 0) {
278 Log.w(TAG, "untagSocket(" + fd.getInt$() + ") failed with errno " + errno);
279 }
280 }
281 }
282
283 private static native int native_tagSocketFd(FileDescriptor fd, int tag, int uid);
284 private static native int native_untagSocketFd(FileDescriptor fd);
285
286 private static class UidTag {
287 public int tag = -1;
288 public int uid = -1;
289 }
290
291 private static ThreadLocal<UidTag> sThreadUidTag = new ThreadLocal<UidTag>() {
292 @Override
293 protected UidTag initialValue() {
294 return new UidTag();
295 }
296 };
297
Junyu Lai8e58c822022-01-17 17:05:30 +0000298 /**
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700299 * Set active tag to use when accounting {@link Socket} traffic originating
300 * from the current thread. Only one active tag per thread is supported.
301 * <p>
302 * Changes only take effect during subsequent calls to
303 * {@link #tagSocket(Socket)}.
Jeff Sharkey987f5ff2011-09-16 01:52:49 -0700304 * <p>
305 * Tags between {@code 0xFFFFFF00} and {@code 0xFFFFFFFF} are reserved and
306 * used internally by system services like {@link DownloadManager} when
307 * performing traffic on behalf of an application.
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700308 *
309 * @see #clearThreadStatsTag()
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700310 */
Jeff Sharkey92790062011-06-24 17:05:24 -0700311 public static void setThreadStatsTag(int tag) {
Lorenzo Colittid2ae7392022-01-29 21:07:33 +0900312 getAndSetThreadStatsTag(tag);
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700313 }
314
Jeff Sharkey92790062011-06-24 17:05:24 -0700315 /**
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600316 * Set active tag to use when accounting {@link Socket} traffic originating
Jeff Sharkey289eac12017-01-19 11:55:54 -0700317 * from the current thread. Only one active tag per thread is supported.
318 * <p>
319 * Changes only take effect during subsequent calls to
320 * {@link #tagSocket(Socket)}.
321 * <p>
322 * Tags between {@code 0xFFFFFF00} and {@code 0xFFFFFFFF} are reserved and
323 * used internally by system services like {@link DownloadManager} when
324 * performing traffic on behalf of an application.
325 *
326 * @return the current tag for the calling thread, which can be used to
327 * restore any existing values after a nested operation is finished
328 */
329 public static int getAndSetThreadStatsTag(int tag) {
Lorenzo Colittid2ae7392022-01-29 21:07:33 +0900330 final int old = sThreadUidTag.get().tag;
331 sThreadUidTag.get().tag = tag;
332 return old;
Jeff Sharkey289eac12017-01-19 11:55:54 -0700333 }
334
335 /**
336 * Set active tag to use when accounting {@link Socket} traffic originating
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600337 * from the current thread. The tag used internally is well-defined to
338 * distinguish all backup-related traffic.
339 *
Christopher Tate5a1878d2014-08-06 14:19:56 -0700340 * @hide
341 */
342 @SystemApi
343 public static void setThreadStatsTagBackup() {
344 setThreadStatsTag(TAG_SYSTEM_BACKUP);
345 }
346
347 /**
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600348 * Set active tag to use when accounting {@link Socket} traffic originating
349 * from the current thread. The tag used internally is well-defined to
350 * distinguish all restore-related traffic.
351 *
Christopher Tatec1c71fd2015-11-10 10:49:20 -0800352 * @hide
353 */
354 @SystemApi
355 public static void setThreadStatsTagRestore() {
356 setThreadStatsTag(TAG_SYSTEM_RESTORE);
357 }
358
359 /**
Jeff Sharkey8af5ad12017-06-26 19:50:41 -0600360 * Set active tag to use when accounting {@link Socket} traffic originating
361 * from the current thread. The tag used internally is well-defined to
Jeff Sharkeyb1f97ac2017-08-11 15:04:12 -0600362 * distinguish all code (typically APKs) downloaded by an app store on
363 * behalf of the app, such as updates.
Jeff Sharkey8af5ad12017-06-26 19:50:41 -0600364 *
365 * @hide
366 */
367 @SystemApi
Jeff Sharkeyb1f97ac2017-08-11 15:04:12 -0600368 public static void setThreadStatsTagApp() {
369 setThreadStatsTag(TAG_SYSTEM_APP);
Jeff Sharkey8af5ad12017-06-26 19:50:41 -0600370 }
371
372 /**
Junyu Laiab2c35e2022-01-18 02:46:23 +0000373 * Set active tag to use when accounting {@link Socket} traffic originating
374 * from the current thread. The tag used internally is well-defined to
375 * distinguish all download provider traffic.
376 *
377 * @hide
378 */
379 @SystemApi
380 public static void setThreadStatsTagDownload() {
381 setThreadStatsTag(TAG_SYSTEM_DOWNLOAD);
382 }
383
384 /**
Alon Albert2c295f02011-07-19 11:16:09 +0300385 * Get the active tag used when accounting {@link Socket} traffic originating
386 * from the current thread. Only one active tag per thread is supported.
387 * {@link #tagSocket(Socket)}.
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700388 *
389 * @see #setThreadStatsTag(int)
Alon Albert2c295f02011-07-19 11:16:09 +0300390 */
391 public static int getThreadStatsTag() {
Lorenzo Colittid2ae7392022-01-29 21:07:33 +0900392 return sThreadUidTag.get().tag;
Alon Albert2c295f02011-07-19 11:16:09 +0300393 }
394
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700395 /**
396 * Clear any active tag set to account {@link Socket} traffic originating
397 * from the current thread.
398 *
399 * @see #setThreadStatsTag(int)
400 */
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700401 public static void clearThreadStatsTag() {
Lorenzo Colittid2ae7392022-01-29 21:07:33 +0900402 sThreadUidTag.get().tag = -1;
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700403 }
404
405 /**
406 * Set specific UID to use when accounting {@link Socket} traffic
407 * originating from the current thread. Designed for use when performing an
Jeff Sharkey17a38752018-03-26 13:11:33 -0600408 * operation on behalf of another application, or when another application
409 * is performing operations on your behalf.
410 * <p>
411 * Any app can <em>accept</em> blame for traffic performed on a socket
412 * originally created by another app by calling this method with the
413 * {@link android.system.Os#getuid()} value. However, only apps holding the
414 * {@code android.Manifest.permission#UPDATE_DEVICE_STATS} permission may
415 * <em>assign</em> blame to another UIDs.
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700416 * <p>
417 * Changes only take effect during subsequent calls to
418 * {@link #tagSocket(Socket)}.
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700419 */
Aurimas Liutikas9de1e0e2020-11-12 18:29:11 -0800420 @SuppressLint("RequiresPermission")
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700421 public static void setThreadStatsUid(int uid) {
Lorenzo Colittid2ae7392022-01-29 21:07:33 +0900422 sThreadUidTag.get().uid = uid;
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700423 }
424
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600425 /**
Jeff Sharkey17a38752018-03-26 13:11:33 -0600426 * Get the active UID used when accounting {@link Socket} traffic originating
427 * from the current thread. Only one active tag per thread is supported.
428 * {@link #tagSocket(Socket)}.
429 *
430 * @see #setThreadStatsUid(int)
431 */
432 public static int getThreadStatsUid() {
Lorenzo Colittid2ae7392022-01-29 21:07:33 +0900433 return sThreadUidTag.get().uid;
Jeff Sharkey17a38752018-03-26 13:11:33 -0600434 }
435
436 /**
Jeff Sharkey1fb74312017-11-29 11:18:23 -0700437 * Set specific UID to use when accounting {@link Socket} traffic
438 * originating from the current thread as the calling UID. Designed for use
439 * when another application is performing operations on your behalf.
440 * <p>
441 * Changes only take effect during subsequent calls to
442 * {@link #tagSocket(Socket)}.
Jeff Sharkey17a38752018-03-26 13:11:33 -0600443 *
444 * @removed
445 * @deprecated use {@link #setThreadStatsUid(int)} instead.
Jeff Sharkey1fb74312017-11-29 11:18:23 -0700446 */
Jeff Sharkey17a38752018-03-26 13:11:33 -0600447 @Deprecated
Jeff Sharkey1fb74312017-11-29 11:18:23 -0700448 public static void setThreadStatsUidSelf() {
449 setThreadStatsUid(android.os.Process.myUid());
450 }
451
452 /**
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600453 * Clear any active UID set to account {@link Socket} traffic originating
454 * from the current thread.
455 *
456 * @see #setThreadStatsUid(int)
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600457 */
Aurimas Liutikas9de1e0e2020-11-12 18:29:11 -0800458 @SuppressLint("RequiresPermission")
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700459 public static void clearThreadStatsUid() {
Lorenzo Colittid2ae7392022-01-29 21:07:33 +0900460 setThreadStatsUid(-1);
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700461 }
462
463 /**
464 * Tag the given {@link Socket} with any statistics parameters active for
465 * the current thread. Subsequent calls always replace any existing
466 * parameters. When finished, call {@link #untagSocket(Socket)} to remove
467 * statistics parameters.
468 *
Jeff Sharkey92790062011-06-24 17:05:24 -0700469 * @see #setThreadStatsTag(int)
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700470 */
471 public static void tagSocket(Socket socket) throws SocketException {
Jesse Wilsonb05f41c2011-06-28 19:06:31 -0700472 SocketTagger.get().tag(socket);
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700473 }
474
475 /**
476 * Remove any statistics parameters from the given {@link Socket}.
koprivac134e242018-07-23 18:19:39 -0700477 * <p>
478 * In Android 8.1 (API level 27) and lower, a socket is automatically
479 * untagged when it's sent to another process using binder IPC with a
480 * {@code ParcelFileDescriptor} container. In Android 9.0 (API level 28)
481 * and higher, the socket tag is kept when the socket is sent to another
482 * process using binder IPC. You can mimic the previous behavior by
483 * calling {@code untagSocket()} before sending the socket to another
484 * process.
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700485 */
486 public static void untagSocket(Socket socket) throws SocketException {
Jesse Wilsonb05f41c2011-06-28 19:06:31 -0700487 SocketTagger.get().untag(socket);
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700488 }
489
490 /**
Jeff Sharkey7b124cb2015-12-04 15:21:52 -0700491 * Tag the given {@link DatagramSocket} with any statistics parameters
492 * active for the current thread. Subsequent calls always replace any
493 * existing parameters. When finished, call
494 * {@link #untagDatagramSocket(DatagramSocket)} to remove statistics
495 * parameters.
496 *
497 * @see #setThreadStatsTag(int)
Jeff Sharkey7b124cb2015-12-04 15:21:52 -0700498 */
499 public static void tagDatagramSocket(DatagramSocket socket) throws SocketException {
500 SocketTagger.get().tag(socket);
501 }
502
503 /**
504 * Remove any statistics parameters from the given {@link DatagramSocket}.
505 */
506 public static void untagDatagramSocket(DatagramSocket socket) throws SocketException {
507 SocketTagger.get().untag(socket);
508 }
509
510 /**
Jeff Sharkey1fb74312017-11-29 11:18:23 -0700511 * Tag the given {@link FileDescriptor} socket with any statistics
512 * parameters active for the current thread. Subsequent calls always replace
513 * any existing parameters. When finished, call
514 * {@link #untagFileDescriptor(FileDescriptor)} to remove statistics
515 * parameters.
516 *
517 * @see #setThreadStatsTag(int)
518 */
519 public static void tagFileDescriptor(FileDescriptor fd) throws IOException {
520 SocketTagger.get().tag(fd);
521 }
522
523 /**
524 * Remove any statistics parameters from the given {@link FileDescriptor}
525 * socket.
526 */
527 public static void untagFileDescriptor(FileDescriptor fd) throws IOException {
528 SocketTagger.get().untag(fd);
529 }
530
531 /**
Jeff Sharkey33936ac2011-05-17 14:55:15 -0700532 * Start profiling data usage for current UID. Only one profiling session
533 * can be active at a time.
534 *
535 * @hide
536 */
537 public static void startDataProfiling(Context context) {
538 synchronized (sProfilingLock) {
539 if (sActiveProfilingStart != null) {
540 throw new IllegalStateException("already profiling data");
541 }
542
543 // take snapshot in time; we calculate delta later
Jeff Sharkey7407e092011-07-19 23:47:12 -0700544 sActiveProfilingStart = getDataLayerSnapshotForUid(context);
Jeff Sharkey33936ac2011-05-17 14:55:15 -0700545 }
546 }
547
548 /**
549 * Stop profiling data usage for current UID.
550 *
551 * @return Detailed {@link NetworkStats} of data that occurred since last
552 * {@link #startDataProfiling(Context)} call.
553 * @hide
554 */
555 public static NetworkStats stopDataProfiling(Context context) {
556 synchronized (sProfilingLock) {
557 if (sActiveProfilingStart == null) {
558 throw new IllegalStateException("not profiling data");
559 }
560
Jeff Sharkeyef7bded2012-01-10 17:24:44 -0800561 // subtract starting values and return delta
562 final NetworkStats profilingStop = getDataLayerSnapshotForUid(context);
563 final NetworkStats profilingDelta = NetworkStats.subtract(
Jeff Sharkeybfe82682012-01-11 18:38:16 -0800564 profilingStop, sActiveProfilingStart, null, null);
Jeff Sharkeyef7bded2012-01-10 17:24:44 -0800565 sActiveProfilingStart = null;
566 return profilingDelta;
Jeff Sharkey33936ac2011-05-17 14:55:15 -0700567 }
568 }
569
570 /**
Jeff Sharkey60ca0232011-08-24 15:42:09 -0700571 * Increment count of network operations performed under the accounting tag
572 * currently active on the calling thread. This can be used to derive
573 * bytes-per-operation.
574 *
575 * @param operationCount Number of operations to increment count by.
576 */
577 public static void incrementOperationCount(int operationCount) {
578 final int tag = getThreadStatsTag();
579 incrementOperationCount(tag, operationCount);
580 }
581
582 /**
Jeff Sharkey7407e092011-07-19 23:47:12 -0700583 * Increment count of network operations performed under the given
584 * accounting tag. This can be used to derive bytes-per-operation.
585 *
586 * @param tag Accounting tag used in {@link #setThreadStatsTag(int)}.
587 * @param operationCount Number of operations to increment count by.
588 */
589 public static void incrementOperationCount(int tag, int operationCount) {
Jeff Sharkey7407e092011-07-19 23:47:12 -0700590 final int uid = android.os.Process.myUid();
591 try {
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700592 getStatsService().incrementOperationCount(uid, tag, operationCount);
Jeff Sharkey7407e092011-07-19 23:47:12 -0700593 } catch (RemoteException e) {
Jeff Sharkeybc08d072016-02-26 13:03:01 -0700594 throw e.rethrowFromSystemServer();
Jeff Sharkey7407e092011-07-19 23:47:12 -0700595 }
596 }
597
Jeff Sharkey920d9042012-04-06 11:12:08 -0700598 /** {@hide} */
599 public static void closeQuietly(INetworkStatsSession session) {
600 // TODO: move to NetworkStatsService once it exists
601 if (session != null) {
602 try {
603 session.close();
604 } catch (RuntimeException rethrown) {
605 throw rethrown;
606 } catch (Exception ignored) {
607 }
608 }
609 }
610
Chenbo Feng905f0342018-01-25 11:43:52 -0800611 private static long addIfSupported(long stat) {
612 return (stat == UNSUPPORTED) ? 0 : stat;
613 }
614
Jeff Sharkey7407e092011-07-19 23:47:12 -0700615 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700616 * Return number of packets transmitted across mobile networks since device
617 * boot. Counts packets across all mobile network interfaces, and always
618 * increases monotonically since device boot. Statistics are measured at the
619 * network layer, so they include both TCP and UDP usage.
620 * <p>
621 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
622 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800623 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700624 public static long getMobileTxPackets() {
625 long total = 0;
626 for (String iface : getMobileIfaces()) {
Chenbo Feng905f0342018-01-25 11:43:52 -0800627 total += addIfSupported(getTxPackets(iface));
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700628 }
629 return total;
630 }
Ken Shirriffae521152009-12-07 15:56:05 -0800631
632 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700633 * Return number of packets received across mobile networks since device
634 * boot. Counts packets across all mobile network interfaces, and always
635 * increases monotonically since device boot. Statistics are measured at the
636 * network layer, so they include both TCP and UDP usage.
637 * <p>
638 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
639 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800640 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700641 public static long getMobileRxPackets() {
642 long total = 0;
643 for (String iface : getMobileIfaces()) {
Chenbo Feng905f0342018-01-25 11:43:52 -0800644 total += addIfSupported(getRxPackets(iface));
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700645 }
646 return total;
647 }
Ken Shirriffae521152009-12-07 15:56:05 -0800648
649 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700650 * Return number of bytes transmitted across mobile networks since device
651 * boot. Counts packets across all mobile network interfaces, and always
652 * increases monotonically since device boot. Statistics are measured at the
653 * network layer, so they include both TCP and UDP usage.
654 * <p>
655 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
656 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800657 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700658 public static long getMobileTxBytes() {
659 long total = 0;
660 for (String iface : getMobileIfaces()) {
Chenbo Feng905f0342018-01-25 11:43:52 -0800661 total += addIfSupported(getTxBytes(iface));
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700662 }
663 return total;
664 }
Ken Shirriffae521152009-12-07 15:56:05 -0800665
666 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700667 * Return number of bytes received across mobile networks since device boot.
668 * Counts packets across all mobile network interfaces, and always increases
669 * monotonically since device boot. Statistics are measured at the network
670 * layer, so they include both TCP and UDP usage.
671 * <p>
672 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
673 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800674 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700675 public static long getMobileRxBytes() {
676 long total = 0;
677 for (String iface : getMobileIfaces()) {
Chenbo Feng905f0342018-01-25 11:43:52 -0800678 total += addIfSupported(getRxBytes(iface));
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700679 }
680 return total;
681 }
Ken Shirriffae521152009-12-07 15:56:05 -0800682
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800683 /** {@hide} */
Mathew Inwoodfe2fed72020-11-04 09:29:36 +0000684 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800685 public static long getMobileTcpRxPackets() {
686 long total = 0;
687 for (String iface : getMobileIfaces()) {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800688 long stat = UNSUPPORTED;
689 try {
690 stat = getStatsService().getIfaceStats(iface, TYPE_TCP_RX_PACKETS);
691 } catch (RemoteException e) {
692 throw e.rethrowFromSystemServer();
693 }
Chenbo Feng905f0342018-01-25 11:43:52 -0800694 total += addIfSupported(stat);
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800695 }
696 return total;
697 }
698
699 /** {@hide} */
Mathew Inwoodfe2fed72020-11-04 09:29:36 +0000700 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800701 public static long getMobileTcpTxPackets() {
702 long total = 0;
703 for (String iface : getMobileIfaces()) {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800704 long stat = UNSUPPORTED;
705 try {
706 stat = getStatsService().getIfaceStats(iface, TYPE_TCP_TX_PACKETS);
707 } catch (RemoteException e) {
708 throw e.rethrowFromSystemServer();
709 }
Chenbo Feng905f0342018-01-25 11:43:52 -0800710 total += addIfSupported(stat);
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800711 }
712 return total;
713 }
714
Aaron Huang443651d2019-09-27 22:31:22 +0800715 /**
junyulai3154d512020-09-29 14:19:24 +0800716 * Return the number of packets transmitted on the specified interface since the interface
717 * was created. Statistics are measured at the network layer, so both TCP and
Aaron Huang443651d2019-09-27 22:31:22 +0800718 * UDP usage are included.
719 *
junyulai3154d512020-09-29 14:19:24 +0800720 * Note that the returned values are partial statistics that do not count data from several
721 * sources and do not apply several adjustments that are necessary for correctness, such
722 * as adjusting for VPN apps, IPv6-in-IPv4 translation, etc. These values can be used to
723 * determine whether traffic is being transferred on the specific interface but are not a
724 * substitute for the more accurate statistics provided by the {@link NetworkStatsManager}
725 * APIs.
726 *
Aaron Huang443651d2019-09-27 22:31:22 +0800727 * @param iface The name of the interface.
728 * @return The number of transmitted packets.
729 */
730 public static long getTxPackets(@NonNull String iface) {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800731 try {
732 return getStatsService().getIfaceStats(iface, TYPE_TX_PACKETS);
733 } catch (RemoteException e) {
734 throw e.rethrowFromSystemServer();
735 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700736 }
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800737
Aaron Huang443651d2019-09-27 22:31:22 +0800738 /**
junyulai3154d512020-09-29 14:19:24 +0800739 * Return the number of packets received on the specified interface since the interface was
740 * created. Statistics are measured at the network layer, so both TCP
Aaron Huang443651d2019-09-27 22:31:22 +0800741 * and UDP usage are included.
742 *
junyulai3154d512020-09-29 14:19:24 +0800743 * Note that the returned values are partial statistics that do not count data from several
744 * sources and do not apply several adjustments that are necessary for correctness, such
745 * as adjusting for VPN apps, IPv6-in-IPv4 translation, etc. These values can be used to
746 * determine whether traffic is being transferred on the specific interface but are not a
747 * substitute for the more accurate statistics provided by the {@link NetworkStatsManager}
748 * APIs.
749 *
Aaron Huang443651d2019-09-27 22:31:22 +0800750 * @param iface The name of the interface.
751 * @return The number of received packets.
752 */
753 public static long getRxPackets(@NonNull String iface) {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800754 try {
755 return getStatsService().getIfaceStats(iface, TYPE_RX_PACKETS);
756 } catch (RemoteException e) {
757 throw e.rethrowFromSystemServer();
758 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700759 }
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800760
junyulai3154d512020-09-29 14:19:24 +0800761 /**
762 * Return the number of bytes transmitted on the specified interface since the interface
763 * was created. Statistics are measured at the network layer, so both TCP and
764 * UDP usage are included.
765 *
766 * Note that the returned values are partial statistics that do not count data from several
767 * sources and do not apply several adjustments that are necessary for correctness, such
768 * as adjusting for VPN apps, IPv6-in-IPv4 translation, etc. These values can be used to
769 * determine whether traffic is being transferred on the specific interface but are not a
770 * substitute for the more accurate statistics provided by the {@link NetworkStatsManager}
771 * APIs.
772 *
773 * @param iface The name of the interface.
774 * @return The number of transmitted bytes.
775 */
776 public static long getTxBytes(@NonNull String iface) {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800777 try {
778 return getStatsService().getIfaceStats(iface, TYPE_TX_BYTES);
779 } catch (RemoteException e) {
780 throw e.rethrowFromSystemServer();
781 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700782 }
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800783
junyulai3154d512020-09-29 14:19:24 +0800784 /**
785 * Return the number of bytes received on the specified interface since the interface
786 * was created. Statistics are measured at the network layer, so both TCP
787 * and UDP usage are included.
788 *
789 * Note that the returned values are partial statistics that do not count data from several
790 * sources and do not apply several adjustments that are necessary for correctness, such
791 * as adjusting for VPN apps, IPv6-in-IPv4 translation, etc. These values can be used to
792 * determine whether traffic is being transferred on the specific interface but are not a
793 * substitute for the more accurate statistics provided by the {@link NetworkStatsManager}
794 * APIs.
795 *
796 * @param iface The name of the interface.
797 * @return The number of received bytes.
798 */
799 public static long getRxBytes(@NonNull String iface) {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800800 try {
801 return getStatsService().getIfaceStats(iface, TYPE_RX_BYTES);
802 } catch (RemoteException e) {
803 throw e.rethrowFromSystemServer();
804 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700805 }
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800806
Benedict Wong083faee2017-12-03 19:42:36 -0800807 /** {@hide} */
808 @TestApi
809 public static long getLoopbackTxPackets() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800810 try {
811 return getStatsService().getIfaceStats(LOOPBACK_IFACE, TYPE_TX_PACKETS);
812 } catch (RemoteException e) {
813 throw e.rethrowFromSystemServer();
814 }
Benedict Wong083faee2017-12-03 19:42:36 -0800815 }
816
817 /** {@hide} */
818 @TestApi
819 public static long getLoopbackRxPackets() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800820 try {
821 return getStatsService().getIfaceStats(LOOPBACK_IFACE, TYPE_RX_PACKETS);
822 } catch (RemoteException e) {
823 throw e.rethrowFromSystemServer();
824 }
Benedict Wong083faee2017-12-03 19:42:36 -0800825 }
826
827 /** {@hide} */
828 @TestApi
829 public static long getLoopbackTxBytes() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800830 try {
831 return getStatsService().getIfaceStats(LOOPBACK_IFACE, TYPE_TX_BYTES);
832 } catch (RemoteException e) {
833 throw e.rethrowFromSystemServer();
834 }
Benedict Wong083faee2017-12-03 19:42:36 -0800835 }
836
837 /** {@hide} */
838 @TestApi
839 public static long getLoopbackRxBytes() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800840 try {
841 return getStatsService().getIfaceStats(LOOPBACK_IFACE, TYPE_RX_BYTES);
842 } catch (RemoteException e) {
843 throw e.rethrowFromSystemServer();
844 }
Benedict Wong083faee2017-12-03 19:42:36 -0800845 }
846
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800847 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700848 * Return number of packets transmitted since device boot. Counts packets
849 * across all network interfaces, and always increases monotonically since
850 * device boot. Statistics are measured at the network layer, so they
851 * include both TCP and UDP usage.
852 * <p>
853 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
854 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800855 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700856 public static long getTotalTxPackets() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800857 try {
858 return getStatsService().getTotalStats(TYPE_TX_PACKETS);
859 } catch (RemoteException e) {
860 throw e.rethrowFromSystemServer();
861 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700862 }
Ken Shirriffae521152009-12-07 15:56:05 -0800863
864 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700865 * Return number of packets received since device boot. Counts packets
866 * across all network interfaces, and always increases monotonically since
867 * device boot. Statistics are measured at the network layer, so they
868 * include both TCP and UDP usage.
869 * <p>
870 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
871 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800872 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700873 public static long getTotalRxPackets() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800874 try {
875 return getStatsService().getTotalStats(TYPE_RX_PACKETS);
876 } catch (RemoteException e) {
877 throw e.rethrowFromSystemServer();
878 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700879 }
Ken Shirriffae521152009-12-07 15:56:05 -0800880
881 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700882 * Return number of bytes transmitted since device boot. Counts packets
883 * across all network interfaces, and always increases monotonically since
884 * device boot. Statistics are measured at the network layer, so they
885 * include both TCP and UDP usage.
886 * <p>
887 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
888 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800889 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700890 public static long getTotalTxBytes() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800891 try {
892 return getStatsService().getTotalStats(TYPE_TX_BYTES);
893 } catch (RemoteException e) {
894 throw e.rethrowFromSystemServer();
895 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700896 }
Ken Shirriffae521152009-12-07 15:56:05 -0800897
898 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700899 * Return number of bytes received since device boot. Counts packets across
900 * all network interfaces, and always increases monotonically since device
901 * boot. Statistics are measured at the network layer, so they include both
902 * TCP and UDP usage.
903 * <p>
904 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
905 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800906 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700907 public static long getTotalRxBytes() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800908 try {
909 return getStatsService().getTotalStats(TYPE_RX_BYTES);
910 } catch (RemoteException e) {
911 throw e.rethrowFromSystemServer();
912 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700913 }
Ken Shirriffae521152009-12-07 15:56:05 -0800914
915 /**
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800916 * Return number of bytes transmitted by the given UID since device boot.
917 * Counts packets across all network interfaces, and always increases
918 * monotonically since device boot. Statistics are measured at the network
919 * layer, so they include both TCP and UDP usage.
920 * <p>
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700921 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
922 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
923 * <p>
924 * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
925 * report traffic statistics for the calling UID. It will return
926 * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
927 * historical network statistics belonging to other UIDs, use
928 * {@link NetworkStatsManager}.
Ken Shirriffae521152009-12-07 15:56:05 -0800929 *
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800930 * @see android.os.Process#myUid()
931 * @see android.content.pm.ApplicationInfo#uid
Ken Shirriffae521152009-12-07 15:56:05 -0800932 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800933 public static long getUidTxBytes(int uid) {
Chenbo Fengd80a6ed2019-06-17 16:22:28 -0700934 try {
935 return getStatsService().getUidStats(uid, TYPE_TX_BYTES);
936 } catch (RemoteException e) {
937 throw e.rethrowFromSystemServer();
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700938 }
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800939 }
Ken Shirriffae521152009-12-07 15:56:05 -0800940
941 /**
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800942 * Return number of bytes received by the given UID since device boot.
943 * Counts packets across all network interfaces, and always increases
944 * monotonically since device boot. Statistics are measured at the network
945 * layer, so they include both TCP and UDP usage.
946 * <p>
Dianne Hackborne9d72072013-02-25 15:55:37 -0800947 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800948 * {@link #UNSUPPORTED} on devices where statistics aren't available.
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700949 * <p>
950 * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
951 * report traffic statistics for the calling UID. It will return
952 * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
953 * historical network statistics belonging to other UIDs, use
954 * {@link NetworkStatsManager}.
Ken Shirriffae521152009-12-07 15:56:05 -0800955 *
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800956 * @see android.os.Process#myUid()
957 * @see android.content.pm.ApplicationInfo#uid
Ken Shirriffae521152009-12-07 15:56:05 -0800958 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800959 public static long getUidRxBytes(int uid) {
Chenbo Fengd80a6ed2019-06-17 16:22:28 -0700960 try {
961 return getStatsService().getUidStats(uid, TYPE_RX_BYTES);
962 } catch (RemoteException e) {
963 throw e.rethrowFromSystemServer();
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700964 }
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800965 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800966
967 /**
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800968 * Return number of packets transmitted by the given UID since device boot.
969 * Counts packets across all network interfaces, and always increases
970 * monotonically since device boot. Statistics are measured at the network
971 * layer, so they include both TCP and UDP usage.
972 * <p>
Dianne Hackborne9d72072013-02-25 15:55:37 -0800973 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800974 * {@link #UNSUPPORTED} on devices where statistics aren't available.
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700975 * <p>
976 * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
977 * report traffic statistics for the calling UID. It will return
978 * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
979 * historical network statistics belonging to other UIDs, use
980 * {@link NetworkStatsManager}.
Ashish Sharmadf852d82011-01-27 15:52:38 -0800981 *
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800982 * @see android.os.Process#myUid()
983 * @see android.content.pm.ApplicationInfo#uid
Ashish Sharmadf852d82011-01-27 15:52:38 -0800984 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800985 public static long getUidTxPackets(int uid) {
Chenbo Fengd80a6ed2019-06-17 16:22:28 -0700986 try {
987 return getStatsService().getUidStats(uid, TYPE_TX_PACKETS);
988 } catch (RemoteException e) {
989 throw e.rethrowFromSystemServer();
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700990 }
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800991 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800992
993 /**
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800994 * Return number of packets received by the given UID since device boot.
995 * Counts packets across all network interfaces, and always increases
996 * monotonically since device boot. Statistics are measured at the network
997 * layer, so they include both TCP and UDP usage.
998 * <p>
Dianne Hackborne9d72072013-02-25 15:55:37 -0800999 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001000 * {@link #UNSUPPORTED} on devices where statistics aren't available.
Jeff Sharkey27c8a072016-03-09 16:40:15 -07001001 * <p>
1002 * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
1003 * report traffic statistics for the calling UID. It will return
1004 * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
1005 * historical network statistics belonging to other UIDs, use
1006 * {@link NetworkStatsManager}.
Ashish Sharmadf852d82011-01-27 15:52:38 -08001007 *
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001008 * @see android.os.Process#myUid()
1009 * @see android.content.pm.ApplicationInfo#uid
Ashish Sharmadf852d82011-01-27 15:52:38 -08001010 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001011 public static long getUidRxPackets(int uid) {
Chenbo Fengd80a6ed2019-06-17 16:22:28 -07001012 try {
1013 return getStatsService().getUidStats(uid, TYPE_RX_PACKETS);
1014 } catch (RemoteException e) {
1015 throw e.rethrowFromSystemServer();
Jeff Sharkey27c8a072016-03-09 16:40:15 -07001016 }
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001017 }
Ashish Sharmadf852d82011-01-27 15:52:38 -08001018
1019 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -08001020 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001021 * transport layer statistics are no longer available, and will
1022 * always return {@link #UNSUPPORTED}.
1023 * @see #getUidTxBytes(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -08001024 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001025 @Deprecated
1026 public static long getUidTcpTxBytes(int uid) {
1027 return UNSUPPORTED;
1028 }
Ashish Sharmadf852d82011-01-27 15:52:38 -08001029
1030 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -08001031 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001032 * transport layer statistics are no longer available, and will
1033 * always return {@link #UNSUPPORTED}.
1034 * @see #getUidRxBytes(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -08001035 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001036 @Deprecated
1037 public static long getUidTcpRxBytes(int uid) {
1038 return UNSUPPORTED;
1039 }
Ashish Sharmadf852d82011-01-27 15:52:38 -08001040
1041 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -08001042 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001043 * transport layer statistics are no longer available, and will
1044 * always return {@link #UNSUPPORTED}.
1045 * @see #getUidTxBytes(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -08001046 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001047 @Deprecated
1048 public static long getUidUdpTxBytes(int uid) {
1049 return UNSUPPORTED;
1050 }
Ashish Sharmadf852d82011-01-27 15:52:38 -08001051
1052 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -08001053 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001054 * transport layer statistics are no longer available, and will
1055 * always return {@link #UNSUPPORTED}.
1056 * @see #getUidRxBytes(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -08001057 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001058 @Deprecated
1059 public static long getUidUdpRxBytes(int uid) {
1060 return UNSUPPORTED;
1061 }
Ashish Sharmadf852d82011-01-27 15:52:38 -08001062
1063 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -08001064 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001065 * transport layer statistics are no longer available, and will
1066 * always return {@link #UNSUPPORTED}.
1067 * @see #getUidTxPackets(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -08001068 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001069 @Deprecated
1070 public static long getUidTcpTxSegments(int uid) {
1071 return UNSUPPORTED;
1072 }
Ashish Sharmadf852d82011-01-27 15:52:38 -08001073
1074 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -08001075 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001076 * transport layer statistics are no longer available, and will
1077 * always return {@link #UNSUPPORTED}.
1078 * @see #getUidRxPackets(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -08001079 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001080 @Deprecated
1081 public static long getUidTcpRxSegments(int uid) {
1082 return UNSUPPORTED;
1083 }
Ashish Sharmadf852d82011-01-27 15:52:38 -08001084
Ashish Sharmadf852d82011-01-27 15:52:38 -08001085 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -08001086 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001087 * transport layer statistics are no longer available, and will
1088 * always return {@link #UNSUPPORTED}.
1089 * @see #getUidTxPackets(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -08001090 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001091 @Deprecated
1092 public static long getUidUdpTxPackets(int uid) {
1093 return UNSUPPORTED;
1094 }
Ashish Sharmadf852d82011-01-27 15:52:38 -08001095
1096 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -08001097 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001098 * transport layer statistics are no longer available, and will
1099 * always return {@link #UNSUPPORTED}.
1100 * @see #getUidRxPackets(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -08001101 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001102 @Deprecated
1103 public static long getUidUdpRxPackets(int uid) {
1104 return UNSUPPORTED;
1105 }
Jeff Sharkey33936ac2011-05-17 14:55:15 -07001106
1107 /**
1108 * Return detailed {@link NetworkStats} for the current UID. Requires no
1109 * special permission.
1110 */
Jeff Sharkey7407e092011-07-19 23:47:12 -07001111 private static NetworkStats getDataLayerSnapshotForUid(Context context) {
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -07001112 // TODO: take snapshot locally, since proc file is now visible
Jeff Sharkey33936ac2011-05-17 14:55:15 -07001113 final int uid = android.os.Process.myUid();
1114 try {
Jeff Sharkey8308b9b2012-04-10 19:48:07 -07001115 return getStatsService().getDataLayerSnapshotForUid(uid);
Jeff Sharkey33936ac2011-05-17 14:55:15 -07001116 } catch (RemoteException e) {
Jeff Sharkeybc08d072016-02-26 13:03:01 -07001117 throw e.rethrowFromSystemServer();
Jeff Sharkey33936ac2011-05-17 14:55:15 -07001118 }
1119 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -07001120
1121 /**
1122 * Return set of any ifaces associated with mobile networks since boot.
1123 * Interfaces are never removed from this list, so counters should always be
1124 * monotonic.
1125 */
Chalard Jean3cfb4992019-04-09 15:46:21 +09001126 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey8308b9b2012-04-10 19:48:07 -07001127 private static String[] getMobileIfaces() {
1128 try {
1129 return getStatsService().getMobileIfaces();
1130 } catch (RemoteException e) {
Jeff Sharkeybc08d072016-02-26 13:03:01 -07001131 throw e.rethrowFromSystemServer();
Jeff Sharkey8308b9b2012-04-10 19:48:07 -07001132 }
1133 }
1134
junyulaiea236322020-10-06 11:59:56 +08001135 // NOTE: keep these in sync with {@code com_android_server_net_NetworkStatsService.cpp}.
1136 /** {@hide} */
1137 public static final int TYPE_RX_BYTES = 0;
1138 /** {@hide} */
1139 public static final int TYPE_RX_PACKETS = 1;
1140 /** {@hide} */
1141 public static final int TYPE_TX_BYTES = 2;
1142 /** {@hide} */
1143 public static final int TYPE_TX_PACKETS = 3;
1144 /** {@hide} */
1145 public static final int TYPE_TCP_RX_PACKETS = 4;
1146 /** {@hide} */
1147 public static final int TYPE_TCP_TX_PACKETS = 5;
Ken Shirriffae521152009-12-07 15:56:05 -08001148}