blob: c2f0cdfb048cd37846bda5815f13bdedf8642fd8 [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;
Junyu Lai3355c402022-01-25 07:40:06 +000034import android.util.Log;
Jeff Sharkey33936ac2011-05-17 14:55:15 -070035
Jesse Wilsonb05f41c2011-06-28 19:06:31 -070036import com.android.server.NetworkManagementSocketTagger;
Ken Shirriffae521152009-12-07 15:56:05 -080037
Jesse Wilsonb05f41c2011-06-28 19:06:31 -070038import dalvik.system.SocketTagger;
Jeff Sharkey7407e092011-07-19 23:47:12 -070039
Jeff Sharkey1fb74312017-11-29 11:18:23 -070040import java.io.FileDescriptor;
41import java.io.IOException;
Jeff Sharkey7b124cb2015-12-04 15:21:52 -070042import java.net.DatagramSocket;
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -070043import java.net.Socket;
44import java.net.SocketException;
Ken Shirriffae521152009-12-07 15:56:05 -080045
46/**
Jeff Sharkey27c8a072016-03-09 16:40:15 -070047 * Class that provides network traffic statistics. These statistics include
Dan Egnoreaeb7022010-04-07 17:30:50 -070048 * bytes transmitted and received and network packets transmitted and received,
49 * over all interfaces, over the mobile interface, and on a per-UID basis.
Ken Shirriffae521152009-12-07 15:56:05 -080050 * <p>
Jeff Sharkey27c8a072016-03-09 16:40:15 -070051 * These statistics may not be available on all platforms. If the statistics are
52 * not supported by this device, {@link #UNSUPPORTED} will be returned.
53 * <p>
54 * Note that the statistics returned by this class reset and start from zero
55 * after every reboot. To access more robust historical network statistics data,
56 * use {@link NetworkStatsManager} instead.
Ken Shirriffae521152009-12-07 15:56:05 -080057 */
58public class TrafficStats {
Junyu Lai3f7bb332021-12-28 16:18:43 +000059 private static final String TAG = TrafficStats.class.getSimpleName();
Ken Shirriffae521152009-12-07 15:56:05 -080060 /**
61 * The return value to indicate that the device does not support the statistic.
62 */
63 public final static int UNSUPPORTED = -1;
64
Junyu Lai1d3ce852021-12-27 13:56:59 +000065 /** @hide @deprecated use {@code DataUnit} instead to clarify SI-vs-IEC */
Jeff Sharkeya6886af2018-01-07 16:47:31 -070066 @Deprecated
Jeff Sharkey94a315c2012-02-03 14:50:07 -080067 public static final long KB_IN_BYTES = 1024;
Junyu Lai1d3ce852021-12-27 13:56:59 +000068 /** @hide @deprecated use {@code DataUnit} instead to clarify SI-vs-IEC */
Jeff Sharkeya6886af2018-01-07 16:47:31 -070069 @Deprecated
Jeff Sharkey94a315c2012-02-03 14:50:07 -080070 public static final long MB_IN_BYTES = KB_IN_BYTES * 1024;
Junyu Lai1d3ce852021-12-27 13:56:59 +000071 /** @hide @deprecated use {@code DataUnit} instead to clarify SI-vs-IEC */
Jeff Sharkeya6886af2018-01-07 16:47:31 -070072 @Deprecated
Jeff Sharkey94a315c2012-02-03 14:50:07 -080073 public static final long GB_IN_BYTES = MB_IN_BYTES * 1024;
Junyu Lai1d3ce852021-12-27 13:56:59 +000074 /** @hide @deprecated use {@code DataUnit} instead to clarify SI-vs-IEC */
Jeff Sharkeya6886af2018-01-07 16:47:31 -070075 @Deprecated
Jeff Sharkey6f2ba5e2015-03-18 11:27:19 -070076 public static final long TB_IN_BYTES = GB_IN_BYTES * 1024;
Junyu Lai1d3ce852021-12-27 13:56:59 +000077 /** @hide @deprecated use {@code DataUnit} instead to clarify SI-vs-IEC */
Jeff Sharkeya6886af2018-01-07 16:47:31 -070078 @Deprecated
Jeff Sharkey88069072015-06-15 21:09:10 -070079 public static final long PB_IN_BYTES = TB_IN_BYTES * 1024;
Jeff Sharkey94a315c2012-02-03 14:50:07 -080080
Jeff Sharkey1a3eb882011-05-28 20:56:34 -070081 /**
Jeff Sharkeyc04cda62011-06-19 01:08:12 -070082 * Special UID value used when collecting {@link NetworkStatsHistory} for
83 * removed applications.
84 *
85 * @hide
86 */
87 public static final int UID_REMOVED = -4;
88
89 /**
Jeff Sharkey987f5ff2011-09-16 01:52:49 -070090 * Special UID value used when collecting {@link NetworkStatsHistory} for
91 * tethering traffic.
92 *
93 * @hide
94 */
junyulai55041a42019-11-15 17:15:01 +080095 public static final int UID_TETHERING = NetworkStats.UID_TETHERING;
Jeff Sharkey987f5ff2011-09-16 01:52:49 -070096
97 /**
Chalard Jean8a93ab82019-04-09 11:16:56 +090098 * Tag values in this range are reserved for the network stack. The network stack is
99 * running as UID {@link android.os.Process.NETWORK_STACK_UID} when in the mainline
100 * module separate process, and as the system UID otherwise.
101 */
102 /** @hide */
103 @SystemApi
104 public static final int TAG_NETWORK_STACK_RANGE_START = 0xFFFFFD00;
105 /** @hide */
106 @SystemApi
107 public static final int TAG_NETWORK_STACK_RANGE_END = 0xFFFFFEFF;
108
109 /**
110 * Tags between 0xFFFFFF00 and 0xFFFFFFFF are reserved and used internally by system services
111 * like DownloadManager when performing traffic on behalf of an application.
112 */
113 // Please note there is no enforcement of these constants, so do not rely on them to
114 // determine that the caller is a system caller.
115 /** @hide */
116 @SystemApi
117 public static final int TAG_SYSTEM_IMPERSONATION_RANGE_START = 0xFFFFFF00;
118 /** @hide */
119 @SystemApi
120 public static final int TAG_SYSTEM_IMPERSONATION_RANGE_END = 0xFFFFFF0F;
121
122 /**
123 * Tag values between these ranges are reserved for the network stack to do traffic
124 * on behalf of applications. It is a subrange of the range above.
125 */
126 /** @hide */
127 @SystemApi
128 public static final int TAG_NETWORK_STACK_IMPERSONATION_RANGE_START = 0xFFFFFF80;
129 /** @hide */
130 @SystemApi
131 public static final int TAG_NETWORK_STACK_IMPERSONATION_RANGE_END = 0xFFFFFF8F;
132
133 /**
Jeff Sharkey92790062011-06-24 17:05:24 -0700134 * Default tag value for {@link DownloadManager} traffic.
135 *
136 * @hide
137 */
Jeff Sharkey987f5ff2011-09-16 01:52:49 -0700138 public static final int TAG_SYSTEM_DOWNLOAD = 0xFFFFFF01;
Jeff Sharkey92790062011-06-24 17:05:24 -0700139
140 /**
141 * Default tag value for {@link MediaPlayer} traffic.
142 *
143 * @hide
144 */
Jeff Sharkey987f5ff2011-09-16 01:52:49 -0700145 public static final int TAG_SYSTEM_MEDIA = 0xFFFFFF02;
Jeff Sharkey92790062011-06-24 17:05:24 -0700146
147 /**
Christopher Tatec1c71fd2015-11-10 10:49:20 -0800148 * Default tag value for {@link BackupManager} backup traffic; that is,
149 * traffic from the device to the storage backend.
Jeff Sharkey92790062011-06-24 17:05:24 -0700150 *
151 * @hide
152 */
Jeff Sharkey987f5ff2011-09-16 01:52:49 -0700153 public static final int TAG_SYSTEM_BACKUP = 0xFFFFFF03;
Jeff Sharkey92790062011-06-24 17:05:24 -0700154
Christopher Tatec1c71fd2015-11-10 10:49:20 -0800155 /**
156 * Default tag value for {@link BackupManager} restore traffic; that is,
157 * app data retrieved from the storage backend at install time.
158 *
159 * @hide
160 */
161 public static final int TAG_SYSTEM_RESTORE = 0xFFFFFF04;
162
Jeff Sharkey66dca172016-11-21 12:14:50 -0700163 /**
Jeff Sharkeyb1f97ac2017-08-11 15:04:12 -0600164 * Default tag value for code (typically APKs) downloaded by an app store on
165 * behalf of the app, such as updates.
Jeff Sharkey66dca172016-11-21 12:14:50 -0700166 *
167 * @hide
168 */
Jeff Sharkeyb1f97ac2017-08-11 15:04:12 -0600169 public static final int TAG_SYSTEM_APP = 0xFFFFFF05;
Jeff Sharkey8af5ad12017-06-26 19:50:41 -0600170
Chalard Jean8a93ab82019-04-09 11:16:56 +0900171 // TODO : remove this constant when Wifi code is updated
Jeff Sharkey8af5ad12017-06-26 19:50:41 -0600172 /** @hide */
Jeff Sharkey8af5ad12017-06-26 19:50:41 -0600173 public static final int TAG_SYSTEM_PROBE = 0xFFFFFF42;
Jeff Sharkey66dca172016-11-21 12:14:50 -0700174
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700175 private static INetworkStatsService sStatsService;
176
Chalard Jean3cfb4992019-04-09 15:46:21 +0900177 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700178 private synchronized static INetworkStatsService getStatsService() {
179 if (sStatsService == null) {
Junyu Lai92d5b4c2022-01-19 08:33:21 +0000180 throw new IllegalStateException("TrafficStats not initialized, uid="
181 + Binder.getCallingUid());
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700182 }
183 return sStatsService;
184 }
185
Jeff Sharkey92790062011-06-24 17:05:24 -0700186 /**
Jeff Sharkey33936ac2011-05-17 14:55:15 -0700187 * Snapshot of {@link NetworkStats} when the currently active profiling
188 * session started, or {@code null} if no session active.
189 *
190 * @see #startDataProfiling(Context)
191 * @see #stopDataProfiling(Context)
192 */
193 private static NetworkStats sActiveProfilingStart;
194
195 private static Object sProfilingLock = new Object();
196
Benedict Wong083faee2017-12-03 19:42:36 -0800197 private static final String LOOPBACK_IFACE = "lo";
198
Jeff Sharkey33936ac2011-05-17 14:55:15 -0700199 /**
Junyu Lai92d5b4c2022-01-19 08:33:21 +0000200 * Initialization {@link TrafficStats} with the context, to
201 * allow {@link TrafficStats} to fetch the needed binder.
202 *
203 * @param context a long-lived context, such as the application context or system
204 * server context.
205 * @hide
206 */
207 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
208 @SuppressLint("VisiblySynchronized")
209 public static synchronized void init(@NonNull final Context context) {
210 if (sStatsService != null) {
211 throw new IllegalStateException("TrafficStats is already initialized, uid="
212 + Binder.getCallingUid());
213 }
214 final NetworkStatsManager statsManager =
215 context.getSystemService(NetworkStatsManager.class);
Junyu Lai3355c402022-01-25 07:40:06 +0000216 if (statsManager == null) {
217 // TODO: Currently Process.isSupplemental is not working yet, because it depends on
218 // process to run in a certain UID range, which is not true for now. Change this
219 // to Log.wtf once Process.isSupplemental is ready.
220 Log.e(TAG, "TrafficStats not initialized, uid=" + Binder.getCallingUid());
221 return;
222 }
Junyu Lai92d5b4c2022-01-19 08:33:21 +0000223 sStatsService = statsManager.getBinder();
224 }
225
226 /**
Junyu Lai8e58c822022-01-17 17:05:30 +0000227 * Attach the socket tagger implementation to the current process, to
228 * get notified when a socket's {@link FileDescriptor} is assigned to
229 * a thread. See {@link SocketTagger#set(SocketTagger)}.
230 *
231 * @hide
232 */
233 @SystemApi(client = MODULE_LIBRARIES)
234 public static void attachSocketTagger() {
235 NetworkManagementSocketTagger.install();
236 }
237
238 /**
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700239 * Set active tag to use when accounting {@link Socket} traffic originating
240 * from the current thread. Only one active tag per thread is supported.
241 * <p>
242 * Changes only take effect during subsequent calls to
243 * {@link #tagSocket(Socket)}.
Jeff Sharkey987f5ff2011-09-16 01:52:49 -0700244 * <p>
245 * Tags between {@code 0xFFFFFF00} and {@code 0xFFFFFFFF} are reserved and
246 * used internally by system services like {@link DownloadManager} when
247 * performing traffic on behalf of an application.
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700248 *
249 * @see #clearThreadStatsTag()
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700250 */
Jeff Sharkey92790062011-06-24 17:05:24 -0700251 public static void setThreadStatsTag(int tag) {
Jesse Wilsonb05f41c2011-06-28 19:06:31 -0700252 NetworkManagementSocketTagger.setThreadSocketStatsTag(tag);
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700253 }
254
Jeff Sharkey92790062011-06-24 17:05:24 -0700255 /**
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600256 * Set active tag to use when accounting {@link Socket} traffic originating
Jeff Sharkey289eac12017-01-19 11:55:54 -0700257 * from the current thread. Only one active tag per thread is supported.
258 * <p>
259 * Changes only take effect during subsequent calls to
260 * {@link #tagSocket(Socket)}.
261 * <p>
262 * Tags between {@code 0xFFFFFF00} and {@code 0xFFFFFFFF} are reserved and
263 * used internally by system services like {@link DownloadManager} when
264 * performing traffic on behalf of an application.
265 *
266 * @return the current tag for the calling thread, which can be used to
267 * restore any existing values after a nested operation is finished
268 */
269 public static int getAndSetThreadStatsTag(int tag) {
270 return NetworkManagementSocketTagger.setThreadSocketStatsTag(tag);
271 }
272
273 /**
274 * Set active tag to use when accounting {@link Socket} traffic originating
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600275 * from the current thread. The tag used internally is well-defined to
276 * distinguish all backup-related traffic.
277 *
Christopher Tate5a1878d2014-08-06 14:19:56 -0700278 * @hide
279 */
280 @SystemApi
281 public static void setThreadStatsTagBackup() {
282 setThreadStatsTag(TAG_SYSTEM_BACKUP);
283 }
284
285 /**
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600286 * Set active tag to use when accounting {@link Socket} traffic originating
287 * from the current thread. The tag used internally is well-defined to
288 * distinguish all restore-related traffic.
289 *
Christopher Tatec1c71fd2015-11-10 10:49:20 -0800290 * @hide
291 */
292 @SystemApi
293 public static void setThreadStatsTagRestore() {
294 setThreadStatsTag(TAG_SYSTEM_RESTORE);
295 }
296
297 /**
Jeff Sharkey8af5ad12017-06-26 19:50:41 -0600298 * Set active tag to use when accounting {@link Socket} traffic originating
299 * from the current thread. The tag used internally is well-defined to
Jeff Sharkeyb1f97ac2017-08-11 15:04:12 -0600300 * distinguish all code (typically APKs) downloaded by an app store on
301 * behalf of the app, such as updates.
Jeff Sharkey8af5ad12017-06-26 19:50:41 -0600302 *
303 * @hide
304 */
305 @SystemApi
Jeff Sharkeyb1f97ac2017-08-11 15:04:12 -0600306 public static void setThreadStatsTagApp() {
307 setThreadStatsTag(TAG_SYSTEM_APP);
Jeff Sharkey8af5ad12017-06-26 19:50:41 -0600308 }
309
310 /**
Junyu Laiab2c35e2022-01-18 02:46:23 +0000311 * Set active tag to use when accounting {@link Socket} traffic originating
312 * from the current thread. The tag used internally is well-defined to
313 * distinguish all download provider traffic.
314 *
315 * @hide
316 */
317 @SystemApi
318 public static void setThreadStatsTagDownload() {
319 setThreadStatsTag(TAG_SYSTEM_DOWNLOAD);
320 }
321
322 /**
Alon Albert2c295f02011-07-19 11:16:09 +0300323 * Get the active tag used when accounting {@link Socket} traffic originating
324 * from the current thread. Only one active tag per thread is supported.
325 * {@link #tagSocket(Socket)}.
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700326 *
327 * @see #setThreadStatsTag(int)
Alon Albert2c295f02011-07-19 11:16:09 +0300328 */
329 public static int getThreadStatsTag() {
330 return NetworkManagementSocketTagger.getThreadSocketStatsTag();
331 }
332
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700333 /**
334 * Clear any active tag set to account {@link Socket} traffic originating
335 * from the current thread.
336 *
337 * @see #setThreadStatsTag(int)
338 */
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700339 public static void clearThreadStatsTag() {
Jesse Wilsonb05f41c2011-06-28 19:06:31 -0700340 NetworkManagementSocketTagger.setThreadSocketStatsTag(-1);
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700341 }
342
343 /**
344 * Set specific UID to use when accounting {@link Socket} traffic
345 * originating from the current thread. Designed for use when performing an
Jeff Sharkey17a38752018-03-26 13:11:33 -0600346 * operation on behalf of another application, or when another application
347 * is performing operations on your behalf.
348 * <p>
349 * Any app can <em>accept</em> blame for traffic performed on a socket
350 * originally created by another app by calling this method with the
351 * {@link android.system.Os#getuid()} value. However, only apps holding the
352 * {@code android.Manifest.permission#UPDATE_DEVICE_STATS} permission may
353 * <em>assign</em> blame to another UIDs.
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700354 * <p>
355 * Changes only take effect during subsequent calls to
356 * {@link #tagSocket(Socket)}.
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700357 */
Aurimas Liutikas9de1e0e2020-11-12 18:29:11 -0800358 @SuppressLint("RequiresPermission")
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700359 public static void setThreadStatsUid(int uid) {
Jesse Wilsonb05f41c2011-06-28 19:06:31 -0700360 NetworkManagementSocketTagger.setThreadSocketStatsUid(uid);
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700361 }
362
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600363 /**
Jeff Sharkey17a38752018-03-26 13:11:33 -0600364 * Get the active UID used when accounting {@link Socket} traffic originating
365 * from the current thread. Only one active tag per thread is supported.
366 * {@link #tagSocket(Socket)}.
367 *
368 * @see #setThreadStatsUid(int)
369 */
370 public static int getThreadStatsUid() {
371 return NetworkManagementSocketTagger.getThreadSocketStatsUid();
372 }
373
374 /**
Jeff Sharkey1fb74312017-11-29 11:18:23 -0700375 * Set specific UID to use when accounting {@link Socket} traffic
376 * originating from the current thread as the calling UID. Designed for use
377 * when another application is performing operations on your behalf.
378 * <p>
379 * Changes only take effect during subsequent calls to
380 * {@link #tagSocket(Socket)}.
Jeff Sharkey17a38752018-03-26 13:11:33 -0600381 *
382 * @removed
383 * @deprecated use {@link #setThreadStatsUid(int)} instead.
Jeff Sharkey1fb74312017-11-29 11:18:23 -0700384 */
Jeff Sharkey17a38752018-03-26 13:11:33 -0600385 @Deprecated
Jeff Sharkey1fb74312017-11-29 11:18:23 -0700386 public static void setThreadStatsUidSelf() {
387 setThreadStatsUid(android.os.Process.myUid());
388 }
389
390 /**
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600391 * Clear any active UID set to account {@link Socket} traffic originating
392 * from the current thread.
393 *
394 * @see #setThreadStatsUid(int)
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600395 */
Aurimas Liutikas9de1e0e2020-11-12 18:29:11 -0800396 @SuppressLint("RequiresPermission")
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700397 public static void clearThreadStatsUid() {
Jesse Wilsonb05f41c2011-06-28 19:06:31 -0700398 NetworkManagementSocketTagger.setThreadSocketStatsUid(-1);
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700399 }
400
401 /**
402 * Tag the given {@link Socket} with any statistics parameters active for
403 * the current thread. Subsequent calls always replace any existing
404 * parameters. When finished, call {@link #untagSocket(Socket)} to remove
405 * statistics parameters.
406 *
Jeff Sharkey92790062011-06-24 17:05:24 -0700407 * @see #setThreadStatsTag(int)
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700408 */
409 public static void tagSocket(Socket socket) throws SocketException {
Jesse Wilsonb05f41c2011-06-28 19:06:31 -0700410 SocketTagger.get().tag(socket);
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700411 }
412
413 /**
414 * Remove any statistics parameters from the given {@link Socket}.
koprivac134e242018-07-23 18:19:39 -0700415 * <p>
416 * In Android 8.1 (API level 27) and lower, a socket is automatically
417 * untagged when it's sent to another process using binder IPC with a
418 * {@code ParcelFileDescriptor} container. In Android 9.0 (API level 28)
419 * and higher, the socket tag is kept when the socket is sent to another
420 * process using binder IPC. You can mimic the previous behavior by
421 * calling {@code untagSocket()} before sending the socket to another
422 * process.
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700423 */
424 public static void untagSocket(Socket socket) throws SocketException {
Jesse Wilsonb05f41c2011-06-28 19:06:31 -0700425 SocketTagger.get().untag(socket);
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700426 }
427
428 /**
Jeff Sharkey7b124cb2015-12-04 15:21:52 -0700429 * Tag the given {@link DatagramSocket} with any statistics parameters
430 * active for the current thread. Subsequent calls always replace any
431 * existing parameters. When finished, call
432 * {@link #untagDatagramSocket(DatagramSocket)} to remove statistics
433 * parameters.
434 *
435 * @see #setThreadStatsTag(int)
Jeff Sharkey7b124cb2015-12-04 15:21:52 -0700436 */
437 public static void tagDatagramSocket(DatagramSocket socket) throws SocketException {
438 SocketTagger.get().tag(socket);
439 }
440
441 /**
442 * Remove any statistics parameters from the given {@link DatagramSocket}.
443 */
444 public static void untagDatagramSocket(DatagramSocket socket) throws SocketException {
445 SocketTagger.get().untag(socket);
446 }
447
448 /**
Jeff Sharkey1fb74312017-11-29 11:18:23 -0700449 * Tag the given {@link FileDescriptor} socket with any statistics
450 * parameters active for the current thread. Subsequent calls always replace
451 * any existing parameters. When finished, call
452 * {@link #untagFileDescriptor(FileDescriptor)} to remove statistics
453 * parameters.
454 *
455 * @see #setThreadStatsTag(int)
456 */
457 public static void tagFileDescriptor(FileDescriptor fd) throws IOException {
458 SocketTagger.get().tag(fd);
459 }
460
461 /**
462 * Remove any statistics parameters from the given {@link FileDescriptor}
463 * socket.
464 */
465 public static void untagFileDescriptor(FileDescriptor fd) throws IOException {
466 SocketTagger.get().untag(fd);
467 }
468
469 /**
Jeff Sharkey33936ac2011-05-17 14:55:15 -0700470 * Start profiling data usage for current UID. Only one profiling session
471 * can be active at a time.
472 *
473 * @hide
474 */
475 public static void startDataProfiling(Context context) {
476 synchronized (sProfilingLock) {
477 if (sActiveProfilingStart != null) {
478 throw new IllegalStateException("already profiling data");
479 }
480
481 // take snapshot in time; we calculate delta later
Jeff Sharkey7407e092011-07-19 23:47:12 -0700482 sActiveProfilingStart = getDataLayerSnapshotForUid(context);
Jeff Sharkey33936ac2011-05-17 14:55:15 -0700483 }
484 }
485
486 /**
487 * Stop profiling data usage for current UID.
488 *
489 * @return Detailed {@link NetworkStats} of data that occurred since last
490 * {@link #startDataProfiling(Context)} call.
491 * @hide
492 */
493 public static NetworkStats stopDataProfiling(Context context) {
494 synchronized (sProfilingLock) {
495 if (sActiveProfilingStart == null) {
496 throw new IllegalStateException("not profiling data");
497 }
498
Jeff Sharkeyef7bded2012-01-10 17:24:44 -0800499 // subtract starting values and return delta
500 final NetworkStats profilingStop = getDataLayerSnapshotForUid(context);
501 final NetworkStats profilingDelta = NetworkStats.subtract(
Jeff Sharkeybfe82682012-01-11 18:38:16 -0800502 profilingStop, sActiveProfilingStart, null, null);
Jeff Sharkeyef7bded2012-01-10 17:24:44 -0800503 sActiveProfilingStart = null;
504 return profilingDelta;
Jeff Sharkey33936ac2011-05-17 14:55:15 -0700505 }
506 }
507
508 /**
Jeff Sharkey60ca0232011-08-24 15:42:09 -0700509 * Increment count of network operations performed under the accounting tag
510 * currently active on the calling thread. This can be used to derive
511 * bytes-per-operation.
512 *
513 * @param operationCount Number of operations to increment count by.
514 */
515 public static void incrementOperationCount(int operationCount) {
516 final int tag = getThreadStatsTag();
517 incrementOperationCount(tag, operationCount);
518 }
519
520 /**
Jeff Sharkey7407e092011-07-19 23:47:12 -0700521 * Increment count of network operations performed under the given
522 * accounting tag. This can be used to derive bytes-per-operation.
523 *
524 * @param tag Accounting tag used in {@link #setThreadStatsTag(int)}.
525 * @param operationCount Number of operations to increment count by.
526 */
527 public static void incrementOperationCount(int tag, int operationCount) {
Jeff Sharkey7407e092011-07-19 23:47:12 -0700528 final int uid = android.os.Process.myUid();
529 try {
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700530 getStatsService().incrementOperationCount(uid, tag, operationCount);
Jeff Sharkey7407e092011-07-19 23:47:12 -0700531 } catch (RemoteException e) {
Jeff Sharkeybc08d072016-02-26 13:03:01 -0700532 throw e.rethrowFromSystemServer();
Jeff Sharkey7407e092011-07-19 23:47:12 -0700533 }
534 }
535
Jeff Sharkey920d9042012-04-06 11:12:08 -0700536 /** {@hide} */
537 public static void closeQuietly(INetworkStatsSession session) {
538 // TODO: move to NetworkStatsService once it exists
539 if (session != null) {
540 try {
541 session.close();
542 } catch (RuntimeException rethrown) {
543 throw rethrown;
544 } catch (Exception ignored) {
545 }
546 }
547 }
548
Chenbo Feng905f0342018-01-25 11:43:52 -0800549 private static long addIfSupported(long stat) {
550 return (stat == UNSUPPORTED) ? 0 : stat;
551 }
552
Jeff Sharkey7407e092011-07-19 23:47:12 -0700553 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700554 * Return number of packets transmitted across mobile networks since device
555 * boot. Counts packets across all mobile network interfaces, and always
556 * increases monotonically since device boot. Statistics are measured at the
557 * network layer, so they include both TCP and UDP usage.
558 * <p>
559 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
560 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800561 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700562 public static long getMobileTxPackets() {
563 long total = 0;
564 for (String iface : getMobileIfaces()) {
Chenbo Feng905f0342018-01-25 11:43:52 -0800565 total += addIfSupported(getTxPackets(iface));
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700566 }
567 return total;
568 }
Ken Shirriffae521152009-12-07 15:56:05 -0800569
570 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700571 * Return number of packets received across mobile networks since device
572 * boot. Counts packets across all mobile network interfaces, and always
573 * increases monotonically since device boot. Statistics are measured at the
574 * network layer, so they include both TCP and UDP usage.
575 * <p>
576 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
577 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800578 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700579 public static long getMobileRxPackets() {
580 long total = 0;
581 for (String iface : getMobileIfaces()) {
Chenbo Feng905f0342018-01-25 11:43:52 -0800582 total += addIfSupported(getRxPackets(iface));
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700583 }
584 return total;
585 }
Ken Shirriffae521152009-12-07 15:56:05 -0800586
587 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700588 * Return number of bytes transmitted across mobile networks since device
589 * boot. Counts packets across all mobile network interfaces, and always
590 * increases monotonically since device boot. Statistics are measured at the
591 * network layer, so they include both TCP and UDP usage.
592 * <p>
593 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
594 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800595 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700596 public static long getMobileTxBytes() {
597 long total = 0;
598 for (String iface : getMobileIfaces()) {
Chenbo Feng905f0342018-01-25 11:43:52 -0800599 total += addIfSupported(getTxBytes(iface));
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700600 }
601 return total;
602 }
Ken Shirriffae521152009-12-07 15:56:05 -0800603
604 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700605 * Return number of bytes received across mobile networks since device boot.
606 * Counts packets across all mobile network interfaces, and always increases
607 * monotonically since device boot. Statistics are measured at the network
608 * layer, so they include both TCP and UDP usage.
609 * <p>
610 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
611 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800612 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700613 public static long getMobileRxBytes() {
614 long total = 0;
615 for (String iface : getMobileIfaces()) {
Chenbo Feng905f0342018-01-25 11:43:52 -0800616 total += addIfSupported(getRxBytes(iface));
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700617 }
618 return total;
619 }
Ken Shirriffae521152009-12-07 15:56:05 -0800620
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800621 /** {@hide} */
Mathew Inwoodfe2fed72020-11-04 09:29:36 +0000622 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800623 public static long getMobileTcpRxPackets() {
624 long total = 0;
625 for (String iface : getMobileIfaces()) {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800626 long stat = UNSUPPORTED;
627 try {
628 stat = getStatsService().getIfaceStats(iface, TYPE_TCP_RX_PACKETS);
629 } catch (RemoteException e) {
630 throw e.rethrowFromSystemServer();
631 }
Chenbo Feng905f0342018-01-25 11:43:52 -0800632 total += addIfSupported(stat);
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800633 }
634 return total;
635 }
636
637 /** {@hide} */
Mathew Inwoodfe2fed72020-11-04 09:29:36 +0000638 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800639 public static long getMobileTcpTxPackets() {
640 long total = 0;
641 for (String iface : getMobileIfaces()) {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800642 long stat = UNSUPPORTED;
643 try {
644 stat = getStatsService().getIfaceStats(iface, TYPE_TCP_TX_PACKETS);
645 } catch (RemoteException e) {
646 throw e.rethrowFromSystemServer();
647 }
Chenbo Feng905f0342018-01-25 11:43:52 -0800648 total += addIfSupported(stat);
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800649 }
650 return total;
651 }
652
Aaron Huang443651d2019-09-27 22:31:22 +0800653 /**
junyulai3154d512020-09-29 14:19:24 +0800654 * Return the number of packets transmitted on the specified interface since the interface
655 * was created. Statistics are measured at the network layer, so both TCP and
Aaron Huang443651d2019-09-27 22:31:22 +0800656 * UDP usage are included.
657 *
junyulai3154d512020-09-29 14:19:24 +0800658 * Note that the returned values are partial statistics that do not count data from several
659 * sources and do not apply several adjustments that are necessary for correctness, such
660 * as adjusting for VPN apps, IPv6-in-IPv4 translation, etc. These values can be used to
661 * determine whether traffic is being transferred on the specific interface but are not a
662 * substitute for the more accurate statistics provided by the {@link NetworkStatsManager}
663 * APIs.
664 *
Aaron Huang443651d2019-09-27 22:31:22 +0800665 * @param iface The name of the interface.
666 * @return The number of transmitted packets.
667 */
668 public static long getTxPackets(@NonNull String iface) {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800669 try {
670 return getStatsService().getIfaceStats(iface, TYPE_TX_PACKETS);
671 } catch (RemoteException e) {
672 throw e.rethrowFromSystemServer();
673 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700674 }
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800675
Aaron Huang443651d2019-09-27 22:31:22 +0800676 /**
junyulai3154d512020-09-29 14:19:24 +0800677 * Return the number of packets received on the specified interface since the interface was
678 * created. Statistics are measured at the network layer, so both TCP
Aaron Huang443651d2019-09-27 22:31:22 +0800679 * and UDP usage are included.
680 *
junyulai3154d512020-09-29 14:19:24 +0800681 * Note that the returned values are partial statistics that do not count data from several
682 * sources and do not apply several adjustments that are necessary for correctness, such
683 * as adjusting for VPN apps, IPv6-in-IPv4 translation, etc. These values can be used to
684 * determine whether traffic is being transferred on the specific interface but are not a
685 * substitute for the more accurate statistics provided by the {@link NetworkStatsManager}
686 * APIs.
687 *
Aaron Huang443651d2019-09-27 22:31:22 +0800688 * @param iface The name of the interface.
689 * @return The number of received packets.
690 */
691 public static long getRxPackets(@NonNull String iface) {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800692 try {
693 return getStatsService().getIfaceStats(iface, TYPE_RX_PACKETS);
694 } catch (RemoteException e) {
695 throw e.rethrowFromSystemServer();
696 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700697 }
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800698
junyulai3154d512020-09-29 14:19:24 +0800699 /**
700 * Return the number of bytes transmitted on the specified interface since the interface
701 * was created. Statistics are measured at the network layer, so both TCP and
702 * UDP usage are included.
703 *
704 * Note that the returned values are partial statistics that do not count data from several
705 * sources and do not apply several adjustments that are necessary for correctness, such
706 * as adjusting for VPN apps, IPv6-in-IPv4 translation, etc. These values can be used to
707 * determine whether traffic is being transferred on the specific interface but are not a
708 * substitute for the more accurate statistics provided by the {@link NetworkStatsManager}
709 * APIs.
710 *
711 * @param iface The name of the interface.
712 * @return The number of transmitted bytes.
713 */
714 public static long getTxBytes(@NonNull String iface) {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800715 try {
716 return getStatsService().getIfaceStats(iface, TYPE_TX_BYTES);
717 } catch (RemoteException e) {
718 throw e.rethrowFromSystemServer();
719 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700720 }
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800721
junyulai3154d512020-09-29 14:19:24 +0800722 /**
723 * Return the number of bytes received on the specified interface since the interface
724 * was created. Statistics are measured at the network layer, so both TCP
725 * and UDP usage are included.
726 *
727 * Note that the returned values are partial statistics that do not count data from several
728 * sources and do not apply several adjustments that are necessary for correctness, such
729 * as adjusting for VPN apps, IPv6-in-IPv4 translation, etc. These values can be used to
730 * determine whether traffic is being transferred on the specific interface but are not a
731 * substitute for the more accurate statistics provided by the {@link NetworkStatsManager}
732 * APIs.
733 *
734 * @param iface The name of the interface.
735 * @return The number of received bytes.
736 */
737 public static long getRxBytes(@NonNull String iface) {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800738 try {
739 return getStatsService().getIfaceStats(iface, TYPE_RX_BYTES);
740 } catch (RemoteException e) {
741 throw e.rethrowFromSystemServer();
742 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700743 }
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800744
Benedict Wong083faee2017-12-03 19:42:36 -0800745 /** {@hide} */
746 @TestApi
747 public static long getLoopbackTxPackets() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800748 try {
749 return getStatsService().getIfaceStats(LOOPBACK_IFACE, TYPE_TX_PACKETS);
750 } catch (RemoteException e) {
751 throw e.rethrowFromSystemServer();
752 }
Benedict Wong083faee2017-12-03 19:42:36 -0800753 }
754
755 /** {@hide} */
756 @TestApi
757 public static long getLoopbackRxPackets() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800758 try {
759 return getStatsService().getIfaceStats(LOOPBACK_IFACE, TYPE_RX_PACKETS);
760 } catch (RemoteException e) {
761 throw e.rethrowFromSystemServer();
762 }
Benedict Wong083faee2017-12-03 19:42:36 -0800763 }
764
765 /** {@hide} */
766 @TestApi
767 public static long getLoopbackTxBytes() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800768 try {
769 return getStatsService().getIfaceStats(LOOPBACK_IFACE, TYPE_TX_BYTES);
770 } catch (RemoteException e) {
771 throw e.rethrowFromSystemServer();
772 }
Benedict Wong083faee2017-12-03 19:42:36 -0800773 }
774
775 /** {@hide} */
776 @TestApi
777 public static long getLoopbackRxBytes() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800778 try {
779 return getStatsService().getIfaceStats(LOOPBACK_IFACE, TYPE_RX_BYTES);
780 } catch (RemoteException e) {
781 throw e.rethrowFromSystemServer();
782 }
Benedict Wong083faee2017-12-03 19:42:36 -0800783 }
784
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800785 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700786 * Return number of packets transmitted since device boot. Counts packets
787 * across all network interfaces, and always increases monotonically since
788 * device boot. Statistics are measured at the network layer, so they
789 * include both TCP and UDP usage.
790 * <p>
791 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
792 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800793 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700794 public static long getTotalTxPackets() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800795 try {
796 return getStatsService().getTotalStats(TYPE_TX_PACKETS);
797 } catch (RemoteException e) {
798 throw e.rethrowFromSystemServer();
799 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700800 }
Ken Shirriffae521152009-12-07 15:56:05 -0800801
802 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700803 * Return number of packets received since device boot. Counts packets
804 * across all network interfaces, and always increases monotonically since
805 * device boot. Statistics are measured at the network layer, so they
806 * include both TCP and UDP usage.
807 * <p>
808 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
809 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800810 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700811 public static long getTotalRxPackets() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800812 try {
813 return getStatsService().getTotalStats(TYPE_RX_PACKETS);
814 } catch (RemoteException e) {
815 throw e.rethrowFromSystemServer();
816 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700817 }
Ken Shirriffae521152009-12-07 15:56:05 -0800818
819 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700820 * Return number of bytes transmitted since device boot. Counts packets
821 * across all network interfaces, and always increases monotonically since
822 * device boot. Statistics are measured at the network layer, so they
823 * include both TCP and UDP usage.
824 * <p>
825 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
826 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800827 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700828 public static long getTotalTxBytes() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800829 try {
830 return getStatsService().getTotalStats(TYPE_TX_BYTES);
831 } catch (RemoteException e) {
832 throw e.rethrowFromSystemServer();
833 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700834 }
Ken Shirriffae521152009-12-07 15:56:05 -0800835
836 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700837 * Return number of bytes received since device boot. Counts packets across
838 * all network interfaces, and always increases monotonically since device
839 * boot. Statistics are measured at the network layer, so they include both
840 * TCP and UDP usage.
841 * <p>
842 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
843 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800844 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700845 public static long getTotalRxBytes() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800846 try {
847 return getStatsService().getTotalStats(TYPE_RX_BYTES);
848 } catch (RemoteException e) {
849 throw e.rethrowFromSystemServer();
850 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700851 }
Ken Shirriffae521152009-12-07 15:56:05 -0800852
853 /**
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800854 * Return number of bytes transmitted by the given UID since device boot.
855 * Counts packets across all network interfaces, and always increases
856 * monotonically since device boot. Statistics are measured at the network
857 * layer, so they include both TCP and UDP usage.
858 * <p>
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700859 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
860 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
861 * <p>
862 * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
863 * report traffic statistics for the calling UID. It will return
864 * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
865 * historical network statistics belonging to other UIDs, use
866 * {@link NetworkStatsManager}.
Ken Shirriffae521152009-12-07 15:56:05 -0800867 *
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800868 * @see android.os.Process#myUid()
869 * @see android.content.pm.ApplicationInfo#uid
Ken Shirriffae521152009-12-07 15:56:05 -0800870 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800871 public static long getUidTxBytes(int uid) {
Chenbo Fengd80a6ed2019-06-17 16:22:28 -0700872 try {
873 return getStatsService().getUidStats(uid, TYPE_TX_BYTES);
874 } catch (RemoteException e) {
875 throw e.rethrowFromSystemServer();
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700876 }
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800877 }
Ken Shirriffae521152009-12-07 15:56:05 -0800878
879 /**
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800880 * Return number of bytes received by the given UID since device boot.
881 * Counts packets across all network interfaces, and always increases
882 * monotonically since device boot. Statistics are measured at the network
883 * layer, so they include both TCP and UDP usage.
884 * <p>
Dianne Hackborne9d72072013-02-25 15:55:37 -0800885 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800886 * {@link #UNSUPPORTED} on devices where statistics aren't available.
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700887 * <p>
888 * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
889 * report traffic statistics for the calling UID. It will return
890 * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
891 * historical network statistics belonging to other UIDs, use
892 * {@link NetworkStatsManager}.
Ken Shirriffae521152009-12-07 15:56:05 -0800893 *
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800894 * @see android.os.Process#myUid()
895 * @see android.content.pm.ApplicationInfo#uid
Ken Shirriffae521152009-12-07 15:56:05 -0800896 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800897 public static long getUidRxBytes(int uid) {
Chenbo Fengd80a6ed2019-06-17 16:22:28 -0700898 try {
899 return getStatsService().getUidStats(uid, TYPE_RX_BYTES);
900 } catch (RemoteException e) {
901 throw e.rethrowFromSystemServer();
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700902 }
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800903 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800904
905 /**
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800906 * Return number of packets transmitted by the given UID since device boot.
907 * Counts packets across all network interfaces, and always increases
908 * monotonically since device boot. Statistics are measured at the network
909 * layer, so they include both TCP and UDP usage.
910 * <p>
Dianne Hackborne9d72072013-02-25 15:55:37 -0800911 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800912 * {@link #UNSUPPORTED} on devices where statistics aren't available.
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700913 * <p>
914 * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
915 * report traffic statistics for the calling UID. It will return
916 * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
917 * historical network statistics belonging to other UIDs, use
918 * {@link NetworkStatsManager}.
Ashish Sharmadf852d82011-01-27 15:52:38 -0800919 *
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800920 * @see android.os.Process#myUid()
921 * @see android.content.pm.ApplicationInfo#uid
Ashish Sharmadf852d82011-01-27 15:52:38 -0800922 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800923 public static long getUidTxPackets(int uid) {
Chenbo Fengd80a6ed2019-06-17 16:22:28 -0700924 try {
925 return getStatsService().getUidStats(uid, TYPE_TX_PACKETS);
926 } catch (RemoteException e) {
927 throw e.rethrowFromSystemServer();
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700928 }
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800929 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800930
931 /**
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800932 * Return number of packets received by the given UID since device boot.
933 * Counts packets across all network interfaces, and always increases
934 * monotonically since device boot. Statistics are measured at the network
935 * layer, so they include both TCP and UDP usage.
936 * <p>
Dianne Hackborne9d72072013-02-25 15:55:37 -0800937 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800938 * {@link #UNSUPPORTED} on devices where statistics aren't available.
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700939 * <p>
940 * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
941 * report traffic statistics for the calling UID. It will return
942 * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
943 * historical network statistics belonging to other UIDs, use
944 * {@link NetworkStatsManager}.
Ashish Sharmadf852d82011-01-27 15:52:38 -0800945 *
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800946 * @see android.os.Process#myUid()
947 * @see android.content.pm.ApplicationInfo#uid
Ashish Sharmadf852d82011-01-27 15:52:38 -0800948 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800949 public static long getUidRxPackets(int uid) {
Chenbo Fengd80a6ed2019-06-17 16:22:28 -0700950 try {
951 return getStatsService().getUidStats(uid, TYPE_RX_PACKETS);
952 } catch (RemoteException e) {
953 throw e.rethrowFromSystemServer();
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700954 }
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800955 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800956
957 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -0800958 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800959 * transport layer statistics are no longer available, and will
960 * always return {@link #UNSUPPORTED}.
961 * @see #getUidTxBytes(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -0800962 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800963 @Deprecated
964 public static long getUidTcpTxBytes(int uid) {
965 return UNSUPPORTED;
966 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800967
968 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -0800969 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800970 * transport layer statistics are no longer available, and will
971 * always return {@link #UNSUPPORTED}.
972 * @see #getUidRxBytes(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -0800973 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800974 @Deprecated
975 public static long getUidTcpRxBytes(int uid) {
976 return UNSUPPORTED;
977 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800978
979 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -0800980 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800981 * transport layer statistics are no longer available, and will
982 * always return {@link #UNSUPPORTED}.
983 * @see #getUidTxBytes(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -0800984 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800985 @Deprecated
986 public static long getUidUdpTxBytes(int uid) {
987 return UNSUPPORTED;
988 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800989
990 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -0800991 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800992 * transport layer statistics are no longer available, and will
993 * always return {@link #UNSUPPORTED}.
994 * @see #getUidRxBytes(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -0800995 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800996 @Deprecated
997 public static long getUidUdpRxBytes(int uid) {
998 return UNSUPPORTED;
999 }
Ashish Sharmadf852d82011-01-27 15:52:38 -08001000
1001 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -08001002 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001003 * transport layer statistics are no longer available, and will
1004 * always return {@link #UNSUPPORTED}.
1005 * @see #getUidTxPackets(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -08001006 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001007 @Deprecated
1008 public static long getUidTcpTxSegments(int uid) {
1009 return UNSUPPORTED;
1010 }
Ashish Sharmadf852d82011-01-27 15:52:38 -08001011
1012 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -08001013 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001014 * transport layer statistics are no longer available, and will
1015 * always return {@link #UNSUPPORTED}.
1016 * @see #getUidRxPackets(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -08001017 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001018 @Deprecated
1019 public static long getUidTcpRxSegments(int uid) {
1020 return UNSUPPORTED;
1021 }
Ashish Sharmadf852d82011-01-27 15:52:38 -08001022
Ashish Sharmadf852d82011-01-27 15:52:38 -08001023 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -08001024 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001025 * transport layer statistics are no longer available, and will
1026 * always return {@link #UNSUPPORTED}.
1027 * @see #getUidTxPackets(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -08001028 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001029 @Deprecated
1030 public static long getUidUdpTxPackets(int uid) {
1031 return UNSUPPORTED;
1032 }
Ashish Sharmadf852d82011-01-27 15:52:38 -08001033
1034 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -08001035 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001036 * transport layer statistics are no longer available, and will
1037 * always return {@link #UNSUPPORTED}.
1038 * @see #getUidRxPackets(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -08001039 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001040 @Deprecated
1041 public static long getUidUdpRxPackets(int uid) {
1042 return UNSUPPORTED;
1043 }
Jeff Sharkey33936ac2011-05-17 14:55:15 -07001044
1045 /**
1046 * Return detailed {@link NetworkStats} for the current UID. Requires no
1047 * special permission.
1048 */
Jeff Sharkey7407e092011-07-19 23:47:12 -07001049 private static NetworkStats getDataLayerSnapshotForUid(Context context) {
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -07001050 // TODO: take snapshot locally, since proc file is now visible
Jeff Sharkey33936ac2011-05-17 14:55:15 -07001051 final int uid = android.os.Process.myUid();
1052 try {
Jeff Sharkey8308b9b2012-04-10 19:48:07 -07001053 return getStatsService().getDataLayerSnapshotForUid(uid);
Jeff Sharkey33936ac2011-05-17 14:55:15 -07001054 } catch (RemoteException e) {
Jeff Sharkeybc08d072016-02-26 13:03:01 -07001055 throw e.rethrowFromSystemServer();
Jeff Sharkey33936ac2011-05-17 14:55:15 -07001056 }
1057 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -07001058
1059 /**
1060 * Return set of any ifaces associated with mobile networks since boot.
1061 * Interfaces are never removed from this list, so counters should always be
1062 * monotonic.
1063 */
Chalard Jean3cfb4992019-04-09 15:46:21 +09001064 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey8308b9b2012-04-10 19:48:07 -07001065 private static String[] getMobileIfaces() {
1066 try {
1067 return getStatsService().getMobileIfaces();
1068 } catch (RemoteException e) {
Jeff Sharkeybc08d072016-02-26 13:03:01 -07001069 throw e.rethrowFromSystemServer();
Jeff Sharkey8308b9b2012-04-10 19:48:07 -07001070 }
1071 }
1072
junyulaiea236322020-10-06 11:59:56 +08001073 // NOTE: keep these in sync with {@code com_android_server_net_NetworkStatsService.cpp}.
1074 /** {@hide} */
1075 public static final int TYPE_RX_BYTES = 0;
1076 /** {@hide} */
1077 public static final int TYPE_RX_PACKETS = 1;
1078 /** {@hide} */
1079 public static final int TYPE_TX_BYTES = 2;
1080 /** {@hide} */
1081 public static final int TYPE_TX_PACKETS = 3;
1082 /** {@hide} */
1083 public static final int TYPE_TCP_RX_PACKETS = 4;
1084 /** {@hide} */
1085 public static final int TYPE_TCP_TX_PACKETS = 5;
Ken Shirriffae521152009-12-07 15:56:05 -08001086}