blob: 1af32bf5524cc51ed3073b3290c95a4715929207 [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
Aaron Huang443651d2019-09-27 22:31:22 +080019import android.annotation.NonNull;
Junyu Lai3f7bb332021-12-28 16:18:43 +000020import android.annotation.Nullable;
Jeff Sharkey1fb74312017-11-29 11:18:23 -070021import android.annotation.SuppressLint;
Christopher Tate5a1878d2014-08-06 14:19:56 -070022import android.annotation.SystemApi;
Benedict Wong083faee2017-12-03 19:42:36 -080023import android.annotation.TestApi;
Jeff Sharkey92790062011-06-24 17:05:24 -070024import android.app.DownloadManager;
25import android.app.backup.BackupManager;
Jeff Sharkey27c8a072016-03-09 16:40:15 -070026import android.app.usage.NetworkStatsManager;
Artur Satayev164c7562019-12-10 17:47:52 +000027import android.compat.annotation.UnsupportedAppUsage;
Jeff Sharkey33936ac2011-05-17 14:55:15 -070028import android.content.Context;
Jeff Sharkey92790062011-06-24 17:05:24 -070029import android.media.MediaPlayer;
Chalard Jean3cfb4992019-04-09 15:46:21 +090030import android.os.Build;
Junyu Lai3f7bb332021-12-28 16:18:43 +000031import android.os.IBinder;
Jeff Sharkey33936ac2011-05-17 14:55:15 -070032import android.os.RemoteException;
Jeff Sharkey33936ac2011-05-17 14:55:15 -070033
Jesse Wilsonb05f41c2011-06-28 19:06:31 -070034import com.android.server.NetworkManagementSocketTagger;
Ken Shirriffae521152009-12-07 15:56:05 -080035
Jesse Wilsonb05f41c2011-06-28 19:06:31 -070036import dalvik.system.SocketTagger;
Jeff Sharkey7407e092011-07-19 23:47:12 -070037
Jeff Sharkey1fb74312017-11-29 11:18:23 -070038import java.io.FileDescriptor;
39import java.io.IOException;
Junyu Lai3f7bb332021-12-28 16:18:43 +000040import java.lang.reflect.InvocationTargetException;
41import java.lang.reflect.Method;
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 Lai3f7bb332021-12-28 16:18:43 +0000180 sStatsService = getStatsBinder();
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700181 }
182 return sStatsService;
183 }
184
Junyu Lai3f7bb332021-12-28 16:18:43 +0000185 @Nullable
186 private static INetworkStatsService getStatsBinder() {
187 try {
188 final Method getServiceMethod = Class.forName("android.os.ServiceManager")
189 .getDeclaredMethod("getService", new Class[]{String.class});
190 final IBinder binder = (IBinder) getServiceMethod.invoke(
191 null, Context.NETWORK_STATS_SERVICE);
192 return INetworkStatsService.Stub.asInterface(binder);
193 } catch (NoSuchMethodException | ClassNotFoundException | IllegalAccessException
194 | InvocationTargetException e) {
195 throw new NullPointerException("Cannot get INetworkStatsService: " + e);
196 }
197 }
198
Jeff Sharkey92790062011-06-24 17:05:24 -0700199 /**
Jeff Sharkey33936ac2011-05-17 14:55:15 -0700200 * Snapshot of {@link NetworkStats} when the currently active profiling
201 * session started, or {@code null} if no session active.
202 *
203 * @see #startDataProfiling(Context)
204 * @see #stopDataProfiling(Context)
205 */
206 private static NetworkStats sActiveProfilingStart;
207
208 private static Object sProfilingLock = new Object();
209
Benedict Wong083faee2017-12-03 19:42:36 -0800210 private static final String LOOPBACK_IFACE = "lo";
211
Jeff Sharkey33936ac2011-05-17 14:55:15 -0700212 /**
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700213 * Set active tag to use when accounting {@link Socket} traffic originating
214 * from the current thread. Only one active tag per thread is supported.
215 * <p>
216 * Changes only take effect during subsequent calls to
217 * {@link #tagSocket(Socket)}.
Jeff Sharkey987f5ff2011-09-16 01:52:49 -0700218 * <p>
219 * Tags between {@code 0xFFFFFF00} and {@code 0xFFFFFFFF} are reserved and
220 * used internally by system services like {@link DownloadManager} when
221 * performing traffic on behalf of an application.
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700222 *
223 * @see #clearThreadStatsTag()
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700224 */
Jeff Sharkey92790062011-06-24 17:05:24 -0700225 public static void setThreadStatsTag(int tag) {
Jesse Wilsonb05f41c2011-06-28 19:06:31 -0700226 NetworkManagementSocketTagger.setThreadSocketStatsTag(tag);
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700227 }
228
Jeff Sharkey92790062011-06-24 17:05:24 -0700229 /**
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600230 * Set active tag to use when accounting {@link Socket} traffic originating
Jeff Sharkey289eac12017-01-19 11:55:54 -0700231 * from the current thread. Only one active tag per thread is supported.
232 * <p>
233 * Changes only take effect during subsequent calls to
234 * {@link #tagSocket(Socket)}.
235 * <p>
236 * Tags between {@code 0xFFFFFF00} and {@code 0xFFFFFFFF} are reserved and
237 * used internally by system services like {@link DownloadManager} when
238 * performing traffic on behalf of an application.
239 *
240 * @return the current tag for the calling thread, which can be used to
241 * restore any existing values after a nested operation is finished
242 */
243 public static int getAndSetThreadStatsTag(int tag) {
244 return NetworkManagementSocketTagger.setThreadSocketStatsTag(tag);
245 }
246
247 /**
248 * Set active tag to use when accounting {@link Socket} traffic originating
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600249 * from the current thread. The tag used internally is well-defined to
250 * distinguish all backup-related traffic.
251 *
Christopher Tate5a1878d2014-08-06 14:19:56 -0700252 * @hide
253 */
254 @SystemApi
255 public static void setThreadStatsTagBackup() {
256 setThreadStatsTag(TAG_SYSTEM_BACKUP);
257 }
258
259 /**
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600260 * Set active tag to use when accounting {@link Socket} traffic originating
261 * from the current thread. The tag used internally is well-defined to
262 * distinguish all restore-related traffic.
263 *
Christopher Tatec1c71fd2015-11-10 10:49:20 -0800264 * @hide
265 */
266 @SystemApi
267 public static void setThreadStatsTagRestore() {
268 setThreadStatsTag(TAG_SYSTEM_RESTORE);
269 }
270
271 /**
Jeff Sharkey8af5ad12017-06-26 19:50:41 -0600272 * Set active tag to use when accounting {@link Socket} traffic originating
273 * from the current thread. The tag used internally is well-defined to
Jeff Sharkeyb1f97ac2017-08-11 15:04:12 -0600274 * distinguish all code (typically APKs) downloaded by an app store on
275 * behalf of the app, such as updates.
Jeff Sharkey8af5ad12017-06-26 19:50:41 -0600276 *
277 * @hide
278 */
279 @SystemApi
Jeff Sharkeyb1f97ac2017-08-11 15:04:12 -0600280 public static void setThreadStatsTagApp() {
281 setThreadStatsTag(TAG_SYSTEM_APP);
Jeff Sharkey8af5ad12017-06-26 19:50:41 -0600282 }
283
284 /**
Junyu Laiab2c35e2022-01-18 02:46:23 +0000285 * Set active tag to use when accounting {@link Socket} traffic originating
286 * from the current thread. The tag used internally is well-defined to
287 * distinguish all download provider traffic.
288 *
289 * @hide
290 */
291 @SystemApi
292 public static void setThreadStatsTagDownload() {
293 setThreadStatsTag(TAG_SYSTEM_DOWNLOAD);
294 }
295
296 /**
Alon Albert2c295f02011-07-19 11:16:09 +0300297 * Get the active tag used when accounting {@link Socket} traffic originating
298 * from the current thread. Only one active tag per thread is supported.
299 * {@link #tagSocket(Socket)}.
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700300 *
301 * @see #setThreadStatsTag(int)
Alon Albert2c295f02011-07-19 11:16:09 +0300302 */
303 public static int getThreadStatsTag() {
304 return NetworkManagementSocketTagger.getThreadSocketStatsTag();
305 }
306
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700307 /**
308 * Clear any active tag set to account {@link Socket} traffic originating
309 * from the current thread.
310 *
311 * @see #setThreadStatsTag(int)
312 */
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700313 public static void clearThreadStatsTag() {
Jesse Wilsonb05f41c2011-06-28 19:06:31 -0700314 NetworkManagementSocketTagger.setThreadSocketStatsTag(-1);
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700315 }
316
317 /**
318 * Set specific UID to use when accounting {@link Socket} traffic
319 * originating from the current thread. Designed for use when performing an
Jeff Sharkey17a38752018-03-26 13:11:33 -0600320 * operation on behalf of another application, or when another application
321 * is performing operations on your behalf.
322 * <p>
323 * Any app can <em>accept</em> blame for traffic performed on a socket
324 * originally created by another app by calling this method with the
325 * {@link android.system.Os#getuid()} value. However, only apps holding the
326 * {@code android.Manifest.permission#UPDATE_DEVICE_STATS} permission may
327 * <em>assign</em> blame to another UIDs.
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700328 * <p>
329 * Changes only take effect during subsequent calls to
330 * {@link #tagSocket(Socket)}.
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700331 */
Aurimas Liutikas9de1e0e2020-11-12 18:29:11 -0800332 @SuppressLint("RequiresPermission")
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700333 public static void setThreadStatsUid(int uid) {
Jesse Wilsonb05f41c2011-06-28 19:06:31 -0700334 NetworkManagementSocketTagger.setThreadSocketStatsUid(uid);
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700335 }
336
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600337 /**
Jeff Sharkey17a38752018-03-26 13:11:33 -0600338 * Get the active UID used when accounting {@link Socket} traffic originating
339 * from the current thread. Only one active tag per thread is supported.
340 * {@link #tagSocket(Socket)}.
341 *
342 * @see #setThreadStatsUid(int)
343 */
344 public static int getThreadStatsUid() {
345 return NetworkManagementSocketTagger.getThreadSocketStatsUid();
346 }
347
348 /**
Jeff Sharkey1fb74312017-11-29 11:18:23 -0700349 * Set specific UID to use when accounting {@link Socket} traffic
350 * originating from the current thread as the calling UID. Designed for use
351 * when another application is performing operations on your behalf.
352 * <p>
353 * Changes only take effect during subsequent calls to
354 * {@link #tagSocket(Socket)}.
Jeff Sharkey17a38752018-03-26 13:11:33 -0600355 *
356 * @removed
357 * @deprecated use {@link #setThreadStatsUid(int)} instead.
Jeff Sharkey1fb74312017-11-29 11:18:23 -0700358 */
Jeff Sharkey17a38752018-03-26 13:11:33 -0600359 @Deprecated
Jeff Sharkey1fb74312017-11-29 11:18:23 -0700360 public static void setThreadStatsUidSelf() {
361 setThreadStatsUid(android.os.Process.myUid());
362 }
363
364 /**
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600365 * Clear any active UID set to account {@link Socket} traffic originating
366 * from the current thread.
367 *
368 * @see #setThreadStatsUid(int)
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600369 */
Aurimas Liutikas9de1e0e2020-11-12 18:29:11 -0800370 @SuppressLint("RequiresPermission")
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700371 public static void clearThreadStatsUid() {
Jesse Wilsonb05f41c2011-06-28 19:06:31 -0700372 NetworkManagementSocketTagger.setThreadSocketStatsUid(-1);
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700373 }
374
375 /**
376 * Tag the given {@link Socket} with any statistics parameters active for
377 * the current thread. Subsequent calls always replace any existing
378 * parameters. When finished, call {@link #untagSocket(Socket)} to remove
379 * statistics parameters.
380 *
Jeff Sharkey92790062011-06-24 17:05:24 -0700381 * @see #setThreadStatsTag(int)
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700382 */
383 public static void tagSocket(Socket socket) throws SocketException {
Jesse Wilsonb05f41c2011-06-28 19:06:31 -0700384 SocketTagger.get().tag(socket);
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700385 }
386
387 /**
388 * Remove any statistics parameters from the given {@link Socket}.
koprivac134e242018-07-23 18:19:39 -0700389 * <p>
390 * In Android 8.1 (API level 27) and lower, a socket is automatically
391 * untagged when it's sent to another process using binder IPC with a
392 * {@code ParcelFileDescriptor} container. In Android 9.0 (API level 28)
393 * and higher, the socket tag is kept when the socket is sent to another
394 * process using binder IPC. You can mimic the previous behavior by
395 * calling {@code untagSocket()} before sending the socket to another
396 * process.
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700397 */
398 public static void untagSocket(Socket socket) throws SocketException {
Jesse Wilsonb05f41c2011-06-28 19:06:31 -0700399 SocketTagger.get().untag(socket);
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700400 }
401
402 /**
Jeff Sharkey7b124cb2015-12-04 15:21:52 -0700403 * Tag the given {@link DatagramSocket} with any statistics parameters
404 * active for the current thread. Subsequent calls always replace any
405 * existing parameters. When finished, call
406 * {@link #untagDatagramSocket(DatagramSocket)} to remove statistics
407 * parameters.
408 *
409 * @see #setThreadStatsTag(int)
Jeff Sharkey7b124cb2015-12-04 15:21:52 -0700410 */
411 public static void tagDatagramSocket(DatagramSocket socket) throws SocketException {
412 SocketTagger.get().tag(socket);
413 }
414
415 /**
416 * Remove any statistics parameters from the given {@link DatagramSocket}.
417 */
418 public static void untagDatagramSocket(DatagramSocket socket) throws SocketException {
419 SocketTagger.get().untag(socket);
420 }
421
422 /**
Jeff Sharkey1fb74312017-11-29 11:18:23 -0700423 * Tag the given {@link FileDescriptor} socket with any statistics
424 * parameters active for the current thread. Subsequent calls always replace
425 * any existing parameters. When finished, call
426 * {@link #untagFileDescriptor(FileDescriptor)} to remove statistics
427 * parameters.
428 *
429 * @see #setThreadStatsTag(int)
430 */
431 public static void tagFileDescriptor(FileDescriptor fd) throws IOException {
432 SocketTagger.get().tag(fd);
433 }
434
435 /**
436 * Remove any statistics parameters from the given {@link FileDescriptor}
437 * socket.
438 */
439 public static void untagFileDescriptor(FileDescriptor fd) throws IOException {
440 SocketTagger.get().untag(fd);
441 }
442
443 /**
Jeff Sharkey33936ac2011-05-17 14:55:15 -0700444 * Start profiling data usage for current UID. Only one profiling session
445 * can be active at a time.
446 *
447 * @hide
448 */
449 public static void startDataProfiling(Context context) {
450 synchronized (sProfilingLock) {
451 if (sActiveProfilingStart != null) {
452 throw new IllegalStateException("already profiling data");
453 }
454
455 // take snapshot in time; we calculate delta later
Jeff Sharkey7407e092011-07-19 23:47:12 -0700456 sActiveProfilingStart = getDataLayerSnapshotForUid(context);
Jeff Sharkey33936ac2011-05-17 14:55:15 -0700457 }
458 }
459
460 /**
461 * Stop profiling data usage for current UID.
462 *
463 * @return Detailed {@link NetworkStats} of data that occurred since last
464 * {@link #startDataProfiling(Context)} call.
465 * @hide
466 */
467 public static NetworkStats stopDataProfiling(Context context) {
468 synchronized (sProfilingLock) {
469 if (sActiveProfilingStart == null) {
470 throw new IllegalStateException("not profiling data");
471 }
472
Jeff Sharkeyef7bded2012-01-10 17:24:44 -0800473 // subtract starting values and return delta
474 final NetworkStats profilingStop = getDataLayerSnapshotForUid(context);
475 final NetworkStats profilingDelta = NetworkStats.subtract(
Jeff Sharkeybfe82682012-01-11 18:38:16 -0800476 profilingStop, sActiveProfilingStart, null, null);
Jeff Sharkeyef7bded2012-01-10 17:24:44 -0800477 sActiveProfilingStart = null;
478 return profilingDelta;
Jeff Sharkey33936ac2011-05-17 14:55:15 -0700479 }
480 }
481
482 /**
Jeff Sharkey60ca0232011-08-24 15:42:09 -0700483 * Increment count of network operations performed under the accounting tag
484 * currently active on the calling thread. This can be used to derive
485 * bytes-per-operation.
486 *
487 * @param operationCount Number of operations to increment count by.
488 */
489 public static void incrementOperationCount(int operationCount) {
490 final int tag = getThreadStatsTag();
491 incrementOperationCount(tag, operationCount);
492 }
493
494 /**
Jeff Sharkey7407e092011-07-19 23:47:12 -0700495 * Increment count of network operations performed under the given
496 * accounting tag. This can be used to derive bytes-per-operation.
497 *
498 * @param tag Accounting tag used in {@link #setThreadStatsTag(int)}.
499 * @param operationCount Number of operations to increment count by.
500 */
501 public static void incrementOperationCount(int tag, int operationCount) {
Jeff Sharkey7407e092011-07-19 23:47:12 -0700502 final int uid = android.os.Process.myUid();
503 try {
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700504 getStatsService().incrementOperationCount(uid, tag, operationCount);
Jeff Sharkey7407e092011-07-19 23:47:12 -0700505 } catch (RemoteException e) {
Jeff Sharkeybc08d072016-02-26 13:03:01 -0700506 throw e.rethrowFromSystemServer();
Jeff Sharkey7407e092011-07-19 23:47:12 -0700507 }
508 }
509
Jeff Sharkey920d9042012-04-06 11:12:08 -0700510 /** {@hide} */
511 public static void closeQuietly(INetworkStatsSession session) {
512 // TODO: move to NetworkStatsService once it exists
513 if (session != null) {
514 try {
515 session.close();
516 } catch (RuntimeException rethrown) {
517 throw rethrown;
518 } catch (Exception ignored) {
519 }
520 }
521 }
522
Chenbo Feng905f0342018-01-25 11:43:52 -0800523 private static long addIfSupported(long stat) {
524 return (stat == UNSUPPORTED) ? 0 : stat;
525 }
526
Jeff Sharkey7407e092011-07-19 23:47:12 -0700527 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700528 * Return number of packets transmitted across mobile networks since device
529 * boot. Counts packets across all mobile network interfaces, and always
530 * increases monotonically since device boot. Statistics are measured at the
531 * network layer, so they include both TCP and UDP usage.
532 * <p>
533 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
534 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800535 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700536 public static long getMobileTxPackets() {
537 long total = 0;
538 for (String iface : getMobileIfaces()) {
Chenbo Feng905f0342018-01-25 11:43:52 -0800539 total += addIfSupported(getTxPackets(iface));
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700540 }
541 return total;
542 }
Ken Shirriffae521152009-12-07 15:56:05 -0800543
544 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700545 * Return number of packets received across mobile networks since device
546 * boot. Counts packets across all mobile network interfaces, and always
547 * increases monotonically since device boot. Statistics are measured at the
548 * network layer, so they include both TCP and UDP usage.
549 * <p>
550 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
551 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800552 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700553 public static long getMobileRxPackets() {
554 long total = 0;
555 for (String iface : getMobileIfaces()) {
Chenbo Feng905f0342018-01-25 11:43:52 -0800556 total += addIfSupported(getRxPackets(iface));
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700557 }
558 return total;
559 }
Ken Shirriffae521152009-12-07 15:56:05 -0800560
561 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700562 * Return number of bytes transmitted across mobile networks since device
563 * boot. Counts packets across all mobile network interfaces, and always
564 * increases monotonically since device boot. Statistics are measured at the
565 * network layer, so they include both TCP and UDP usage.
566 * <p>
567 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
568 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800569 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700570 public static long getMobileTxBytes() {
571 long total = 0;
572 for (String iface : getMobileIfaces()) {
Chenbo Feng905f0342018-01-25 11:43:52 -0800573 total += addIfSupported(getTxBytes(iface));
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700574 }
575 return total;
576 }
Ken Shirriffae521152009-12-07 15:56:05 -0800577
578 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700579 * Return number of bytes received across mobile networks since device boot.
580 * Counts packets across all mobile network interfaces, and always increases
581 * monotonically since device boot. Statistics are measured at the network
582 * layer, so they include both TCP and UDP usage.
583 * <p>
584 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
585 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800586 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700587 public static long getMobileRxBytes() {
588 long total = 0;
589 for (String iface : getMobileIfaces()) {
Chenbo Feng905f0342018-01-25 11:43:52 -0800590 total += addIfSupported(getRxBytes(iface));
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700591 }
592 return total;
593 }
Ken Shirriffae521152009-12-07 15:56:05 -0800594
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800595 /** {@hide} */
Mathew Inwoodfe2fed72020-11-04 09:29:36 +0000596 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800597 public static long getMobileTcpRxPackets() {
598 long total = 0;
599 for (String iface : getMobileIfaces()) {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800600 long stat = UNSUPPORTED;
601 try {
602 stat = getStatsService().getIfaceStats(iface, TYPE_TCP_RX_PACKETS);
603 } catch (RemoteException e) {
604 throw e.rethrowFromSystemServer();
605 }
Chenbo Feng905f0342018-01-25 11:43:52 -0800606 total += addIfSupported(stat);
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800607 }
608 return total;
609 }
610
611 /** {@hide} */
Mathew Inwoodfe2fed72020-11-04 09:29:36 +0000612 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800613 public static long getMobileTcpTxPackets() {
614 long total = 0;
615 for (String iface : getMobileIfaces()) {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800616 long stat = UNSUPPORTED;
617 try {
618 stat = getStatsService().getIfaceStats(iface, TYPE_TCP_TX_PACKETS);
619 } catch (RemoteException e) {
620 throw e.rethrowFromSystemServer();
621 }
Chenbo Feng905f0342018-01-25 11:43:52 -0800622 total += addIfSupported(stat);
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800623 }
624 return total;
625 }
626
Aaron Huang443651d2019-09-27 22:31:22 +0800627 /**
junyulai3154d512020-09-29 14:19:24 +0800628 * Return the number of packets transmitted on the specified interface since the interface
629 * was created. Statistics are measured at the network layer, so both TCP and
Aaron Huang443651d2019-09-27 22:31:22 +0800630 * UDP usage are included.
631 *
junyulai3154d512020-09-29 14:19:24 +0800632 * Note that the returned values are partial statistics that do not count data from several
633 * sources and do not apply several adjustments that are necessary for correctness, such
634 * as adjusting for VPN apps, IPv6-in-IPv4 translation, etc. These values can be used to
635 * determine whether traffic is being transferred on the specific interface but are not a
636 * substitute for the more accurate statistics provided by the {@link NetworkStatsManager}
637 * APIs.
638 *
Aaron Huang443651d2019-09-27 22:31:22 +0800639 * @param iface The name of the interface.
640 * @return The number of transmitted packets.
641 */
642 public static long getTxPackets(@NonNull String iface) {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800643 try {
644 return getStatsService().getIfaceStats(iface, TYPE_TX_PACKETS);
645 } catch (RemoteException e) {
646 throw e.rethrowFromSystemServer();
647 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700648 }
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800649
Aaron Huang443651d2019-09-27 22:31:22 +0800650 /**
junyulai3154d512020-09-29 14:19:24 +0800651 * Return the number of packets received on the specified interface since the interface was
652 * created. Statistics are measured at the network layer, so both TCP
Aaron Huang443651d2019-09-27 22:31:22 +0800653 * and UDP usage are included.
654 *
junyulai3154d512020-09-29 14:19:24 +0800655 * Note that the returned values are partial statistics that do not count data from several
656 * sources and do not apply several adjustments that are necessary for correctness, such
657 * as adjusting for VPN apps, IPv6-in-IPv4 translation, etc. These values can be used to
658 * determine whether traffic is being transferred on the specific interface but are not a
659 * substitute for the more accurate statistics provided by the {@link NetworkStatsManager}
660 * APIs.
661 *
Aaron Huang443651d2019-09-27 22:31:22 +0800662 * @param iface The name of the interface.
663 * @return The number of received packets.
664 */
665 public static long getRxPackets(@NonNull String iface) {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800666 try {
667 return getStatsService().getIfaceStats(iface, TYPE_RX_PACKETS);
668 } catch (RemoteException e) {
669 throw e.rethrowFromSystemServer();
670 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700671 }
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800672
junyulai3154d512020-09-29 14:19:24 +0800673 /**
674 * Return the number of bytes transmitted on the specified interface since the interface
675 * was created. Statistics are measured at the network layer, so both TCP and
676 * UDP usage are included.
677 *
678 * Note that the returned values are partial statistics that do not count data from several
679 * sources and do not apply several adjustments that are necessary for correctness, such
680 * as adjusting for VPN apps, IPv6-in-IPv4 translation, etc. These values can be used to
681 * determine whether traffic is being transferred on the specific interface but are not a
682 * substitute for the more accurate statistics provided by the {@link NetworkStatsManager}
683 * APIs.
684 *
685 * @param iface The name of the interface.
686 * @return The number of transmitted bytes.
687 */
688 public static long getTxBytes(@NonNull String iface) {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800689 try {
690 return getStatsService().getIfaceStats(iface, TYPE_TX_BYTES);
691 } catch (RemoteException e) {
692 throw e.rethrowFromSystemServer();
693 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700694 }
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800695
junyulai3154d512020-09-29 14:19:24 +0800696 /**
697 * Return the number of bytes received on the specified interface since the interface
698 * was created. Statistics are measured at the network layer, so both TCP
699 * and UDP usage are included.
700 *
701 * Note that the returned values are partial statistics that do not count data from several
702 * sources and do not apply several adjustments that are necessary for correctness, such
703 * as adjusting for VPN apps, IPv6-in-IPv4 translation, etc. These values can be used to
704 * determine whether traffic is being transferred on the specific interface but are not a
705 * substitute for the more accurate statistics provided by the {@link NetworkStatsManager}
706 * APIs.
707 *
708 * @param iface The name of the interface.
709 * @return The number of received bytes.
710 */
711 public static long getRxBytes(@NonNull String iface) {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800712 try {
713 return getStatsService().getIfaceStats(iface, TYPE_RX_BYTES);
714 } catch (RemoteException e) {
715 throw e.rethrowFromSystemServer();
716 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700717 }
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800718
Benedict Wong083faee2017-12-03 19:42:36 -0800719 /** {@hide} */
720 @TestApi
721 public static long getLoopbackTxPackets() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800722 try {
723 return getStatsService().getIfaceStats(LOOPBACK_IFACE, TYPE_TX_PACKETS);
724 } catch (RemoteException e) {
725 throw e.rethrowFromSystemServer();
726 }
Benedict Wong083faee2017-12-03 19:42:36 -0800727 }
728
729 /** {@hide} */
730 @TestApi
731 public static long getLoopbackRxPackets() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800732 try {
733 return getStatsService().getIfaceStats(LOOPBACK_IFACE, TYPE_RX_PACKETS);
734 } catch (RemoteException e) {
735 throw e.rethrowFromSystemServer();
736 }
Benedict Wong083faee2017-12-03 19:42:36 -0800737 }
738
739 /** {@hide} */
740 @TestApi
741 public static long getLoopbackTxBytes() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800742 try {
743 return getStatsService().getIfaceStats(LOOPBACK_IFACE, TYPE_TX_BYTES);
744 } catch (RemoteException e) {
745 throw e.rethrowFromSystemServer();
746 }
Benedict Wong083faee2017-12-03 19:42:36 -0800747 }
748
749 /** {@hide} */
750 @TestApi
751 public static long getLoopbackRxBytes() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800752 try {
753 return getStatsService().getIfaceStats(LOOPBACK_IFACE, TYPE_RX_BYTES);
754 } catch (RemoteException e) {
755 throw e.rethrowFromSystemServer();
756 }
Benedict Wong083faee2017-12-03 19:42:36 -0800757 }
758
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800759 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700760 * Return number of packets transmitted since device boot. Counts packets
761 * across all network interfaces, and always increases monotonically since
762 * device boot. Statistics are measured at the network layer, so they
763 * include both TCP and UDP usage.
764 * <p>
765 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
766 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800767 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700768 public static long getTotalTxPackets() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800769 try {
770 return getStatsService().getTotalStats(TYPE_TX_PACKETS);
771 } catch (RemoteException e) {
772 throw e.rethrowFromSystemServer();
773 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700774 }
Ken Shirriffae521152009-12-07 15:56:05 -0800775
776 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700777 * Return number of packets received since device boot. Counts packets
778 * across all network interfaces, and always increases monotonically since
779 * device boot. Statistics are measured at the network layer, so they
780 * include both TCP and UDP usage.
781 * <p>
782 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
783 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800784 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700785 public static long getTotalRxPackets() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800786 try {
787 return getStatsService().getTotalStats(TYPE_RX_PACKETS);
788 } catch (RemoteException e) {
789 throw e.rethrowFromSystemServer();
790 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700791 }
Ken Shirriffae521152009-12-07 15:56:05 -0800792
793 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700794 * Return number of bytes transmitted since device boot. Counts packets
795 * across all network interfaces, and always increases monotonically since
796 * device boot. Statistics are measured at the network layer, so they
797 * include both TCP and UDP usage.
798 * <p>
799 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
800 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800801 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700802 public static long getTotalTxBytes() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800803 try {
804 return getStatsService().getTotalStats(TYPE_TX_BYTES);
805 } catch (RemoteException e) {
806 throw e.rethrowFromSystemServer();
807 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700808 }
Ken Shirriffae521152009-12-07 15:56:05 -0800809
810 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700811 * Return number of bytes received since device boot. Counts packets across
812 * all network interfaces, and always increases monotonically since device
813 * boot. Statistics are measured at the network layer, so they include both
814 * TCP and UDP usage.
815 * <p>
816 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
817 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800818 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700819 public static long getTotalRxBytes() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800820 try {
821 return getStatsService().getTotalStats(TYPE_RX_BYTES);
822 } catch (RemoteException e) {
823 throw e.rethrowFromSystemServer();
824 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700825 }
Ken Shirriffae521152009-12-07 15:56:05 -0800826
827 /**
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800828 * Return number of bytes transmitted by the given UID since device boot.
829 * Counts packets across all network interfaces, and always increases
830 * monotonically since device boot. Statistics are measured at the network
831 * layer, so they include both TCP and UDP usage.
832 * <p>
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700833 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
834 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
835 * <p>
836 * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
837 * report traffic statistics for the calling UID. It will return
838 * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
839 * historical network statistics belonging to other UIDs, use
840 * {@link NetworkStatsManager}.
Ken Shirriffae521152009-12-07 15:56:05 -0800841 *
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800842 * @see android.os.Process#myUid()
843 * @see android.content.pm.ApplicationInfo#uid
Ken Shirriffae521152009-12-07 15:56:05 -0800844 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800845 public static long getUidTxBytes(int uid) {
Chenbo Fengd80a6ed2019-06-17 16:22:28 -0700846 try {
847 return getStatsService().getUidStats(uid, TYPE_TX_BYTES);
848 } catch (RemoteException e) {
849 throw e.rethrowFromSystemServer();
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700850 }
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800851 }
Ken Shirriffae521152009-12-07 15:56:05 -0800852
853 /**
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800854 * Return number of bytes received 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>
Dianne Hackborne9d72072013-02-25 15:55:37 -0800859 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800860 * {@link #UNSUPPORTED} on devices where statistics aren't available.
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700861 * <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 getUidRxBytes(int uid) {
Chenbo Fengd80a6ed2019-06-17 16:22:28 -0700872 try {
873 return getStatsService().getUidStats(uid, TYPE_RX_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 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800878
879 /**
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800880 * Return number of packets transmitted 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}.
Ashish Sharmadf852d82011-01-27 15:52:38 -0800893 *
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800894 * @see android.os.Process#myUid()
895 * @see android.content.pm.ApplicationInfo#uid
Ashish Sharmadf852d82011-01-27 15:52:38 -0800896 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800897 public static long getUidTxPackets(int uid) {
Chenbo Fengd80a6ed2019-06-17 16:22:28 -0700898 try {
899 return getStatsService().getUidStats(uid, TYPE_TX_PACKETS);
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 received 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 getUidRxPackets(int uid) {
Chenbo Fengd80a6ed2019-06-17 16:22:28 -0700924 try {
925 return getStatsService().getUidStats(uid, TYPE_RX_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 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -0800932 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800933 * transport layer statistics are no longer available, and will
934 * always return {@link #UNSUPPORTED}.
935 * @see #getUidTxBytes(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -0800936 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800937 @Deprecated
938 public static long getUidTcpTxBytes(int uid) {
939 return UNSUPPORTED;
940 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800941
942 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -0800943 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800944 * transport layer statistics are no longer available, and will
945 * always return {@link #UNSUPPORTED}.
946 * @see #getUidRxBytes(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -0800947 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800948 @Deprecated
949 public static long getUidTcpRxBytes(int uid) {
950 return UNSUPPORTED;
951 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800952
953 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -0800954 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800955 * transport layer statistics are no longer available, and will
956 * always return {@link #UNSUPPORTED}.
957 * @see #getUidTxBytes(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -0800958 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800959 @Deprecated
960 public static long getUidUdpTxBytes(int uid) {
961 return UNSUPPORTED;
962 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800963
964 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -0800965 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800966 * transport layer statistics are no longer available, and will
967 * always return {@link #UNSUPPORTED}.
968 * @see #getUidRxBytes(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -0800969 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800970 @Deprecated
971 public static long getUidUdpRxBytes(int uid) {
972 return UNSUPPORTED;
973 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800974
975 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -0800976 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800977 * transport layer statistics are no longer available, and will
978 * always return {@link #UNSUPPORTED}.
979 * @see #getUidTxPackets(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -0800980 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800981 @Deprecated
982 public static long getUidTcpTxSegments(int uid) {
983 return UNSUPPORTED;
984 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800985
986 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -0800987 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800988 * transport layer statistics are no longer available, and will
989 * always return {@link #UNSUPPORTED}.
990 * @see #getUidRxPackets(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -0800991 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800992 @Deprecated
993 public static long getUidTcpRxSegments(int uid) {
994 return UNSUPPORTED;
995 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800996
Ashish Sharmadf852d82011-01-27 15:52:38 -0800997 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -0800998 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800999 * transport layer statistics are no longer available, and will
1000 * always return {@link #UNSUPPORTED}.
1001 * @see #getUidTxPackets(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -08001002 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001003 @Deprecated
1004 public static long getUidUdpTxPackets(int uid) {
1005 return UNSUPPORTED;
1006 }
Ashish Sharmadf852d82011-01-27 15:52:38 -08001007
1008 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -08001009 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001010 * transport layer statistics are no longer available, and will
1011 * always return {@link #UNSUPPORTED}.
1012 * @see #getUidRxPackets(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -08001013 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -08001014 @Deprecated
1015 public static long getUidUdpRxPackets(int uid) {
1016 return UNSUPPORTED;
1017 }
Jeff Sharkey33936ac2011-05-17 14:55:15 -07001018
1019 /**
1020 * Return detailed {@link NetworkStats} for the current UID. Requires no
1021 * special permission.
1022 */
Jeff Sharkey7407e092011-07-19 23:47:12 -07001023 private static NetworkStats getDataLayerSnapshotForUid(Context context) {
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -07001024 // TODO: take snapshot locally, since proc file is now visible
Jeff Sharkey33936ac2011-05-17 14:55:15 -07001025 final int uid = android.os.Process.myUid();
1026 try {
Jeff Sharkey8308b9b2012-04-10 19:48:07 -07001027 return getStatsService().getDataLayerSnapshotForUid(uid);
Jeff Sharkey33936ac2011-05-17 14:55:15 -07001028 } catch (RemoteException e) {
Jeff Sharkeybc08d072016-02-26 13:03:01 -07001029 throw e.rethrowFromSystemServer();
Jeff Sharkey33936ac2011-05-17 14:55:15 -07001030 }
1031 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -07001032
1033 /**
1034 * Return set of any ifaces associated with mobile networks since boot.
1035 * Interfaces are never removed from this list, so counters should always be
1036 * monotonic.
1037 */
Chalard Jean3cfb4992019-04-09 15:46:21 +09001038 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey8308b9b2012-04-10 19:48:07 -07001039 private static String[] getMobileIfaces() {
1040 try {
1041 return getStatsService().getMobileIfaces();
1042 } catch (RemoteException e) {
Jeff Sharkeybc08d072016-02-26 13:03:01 -07001043 throw e.rethrowFromSystemServer();
Jeff Sharkey8308b9b2012-04-10 19:48:07 -07001044 }
1045 }
1046
junyulaiea236322020-10-06 11:59:56 +08001047 // NOTE: keep these in sync with {@code com_android_server_net_NetworkStatsService.cpp}.
1048 /** {@hide} */
1049 public static final int TYPE_RX_BYTES = 0;
1050 /** {@hide} */
1051 public static final int TYPE_RX_PACKETS = 1;
1052 /** {@hide} */
1053 public static final int TYPE_TX_BYTES = 2;
1054 /** {@hide} */
1055 public static final int TYPE_TX_PACKETS = 3;
1056 /** {@hide} */
1057 public static final int TYPE_TCP_RX_PACKETS = 4;
1058 /** {@hide} */
1059 public static final int TYPE_TCP_TX_PACKETS = 5;
Ken Shirriffae521152009-12-07 15:56:05 -08001060}