blob: c803a723ba8334601d622f74605a5c9536bb5277 [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;
Jeff Sharkey1fb74312017-11-29 11:18:23 -070020import android.annotation.SuppressLint;
Christopher Tate5a1878d2014-08-06 14:19:56 -070021import android.annotation.SystemApi;
Benedict Wong083faee2017-12-03 19:42:36 -080022import android.annotation.TestApi;
Jeff Sharkey92790062011-06-24 17:05:24 -070023import android.app.DownloadManager;
24import android.app.backup.BackupManager;
Jeff Sharkey27c8a072016-03-09 16:40:15 -070025import android.app.usage.NetworkStatsManager;
Artur Satayev164c7562019-12-10 17:47:52 +000026import android.compat.annotation.UnsupportedAppUsage;
Jeff Sharkey33936ac2011-05-17 14:55:15 -070027import android.content.Context;
Jeff Sharkey92790062011-06-24 17:05:24 -070028import android.media.MediaPlayer;
Junyu Lai92d5b4c2022-01-19 08:33:21 +000029import android.os.Binder;
Chalard Jean3cfb4992019-04-09 15:46:21 +090030import android.os.Build;
Jeff Sharkey33936ac2011-05-17 14:55:15 -070031import android.os.RemoteException;
Jeff Sharkey33936ac2011-05-17 14:55:15 -070032
Jesse Wilsonb05f41c2011-06-28 19:06:31 -070033import com.android.server.NetworkManagementSocketTagger;
Ken Shirriffae521152009-12-07 15:56:05 -080034
Jesse Wilsonb05f41c2011-06-28 19:06:31 -070035import dalvik.system.SocketTagger;
Jeff Sharkey7407e092011-07-19 23:47:12 -070036
Jeff Sharkey1fb74312017-11-29 11:18:23 -070037import java.io.FileDescriptor;
38import java.io.IOException;
Jeff Sharkey7b124cb2015-12-04 15:21:52 -070039import java.net.DatagramSocket;
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -070040import java.net.Socket;
41import java.net.SocketException;
Ken Shirriffae521152009-12-07 15:56:05 -080042
43/**
Jeff Sharkey27c8a072016-03-09 16:40:15 -070044 * Class that provides network traffic statistics. These statistics include
Dan Egnoreaeb7022010-04-07 17:30:50 -070045 * bytes transmitted and received and network packets transmitted and received,
46 * over all interfaces, over the mobile interface, and on a per-UID basis.
Ken Shirriffae521152009-12-07 15:56:05 -080047 * <p>
Jeff Sharkey27c8a072016-03-09 16:40:15 -070048 * These statistics may not be available on all platforms. If the statistics are
49 * not supported by this device, {@link #UNSUPPORTED} will be returned.
50 * <p>
51 * Note that the statistics returned by this class reset and start from zero
52 * after every reboot. To access more robust historical network statistics data,
53 * use {@link NetworkStatsManager} instead.
Ken Shirriffae521152009-12-07 15:56:05 -080054 */
55public class TrafficStats {
Junyu Lai3f7bb332021-12-28 16:18:43 +000056 private static final String TAG = TrafficStats.class.getSimpleName();
Ken Shirriffae521152009-12-07 15:56:05 -080057 /**
58 * The return value to indicate that the device does not support the statistic.
59 */
60 public final static int UNSUPPORTED = -1;
61
Junyu Lai1d3ce852021-12-27 13:56:59 +000062 /** @hide @deprecated use {@code DataUnit} instead to clarify SI-vs-IEC */
Jeff Sharkeya6886af2018-01-07 16:47:31 -070063 @Deprecated
Jeff Sharkey94a315c2012-02-03 14:50:07 -080064 public static final long KB_IN_BYTES = 1024;
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 MB_IN_BYTES = 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 GB_IN_BYTES = MB_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 Sharkey6f2ba5e2015-03-18 11:27:19 -070073 public static final long TB_IN_BYTES = GB_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 Sharkey88069072015-06-15 21:09:10 -070076 public static final long PB_IN_BYTES = TB_IN_BYTES * 1024;
Jeff Sharkey94a315c2012-02-03 14:50:07 -080077
Jeff Sharkey1a3eb882011-05-28 20:56:34 -070078 /**
Jeff Sharkeyc04cda62011-06-19 01:08:12 -070079 * Special UID value used when collecting {@link NetworkStatsHistory} for
80 * removed applications.
81 *
82 * @hide
83 */
84 public static final int UID_REMOVED = -4;
85
86 /**
Jeff Sharkey987f5ff2011-09-16 01:52:49 -070087 * Special UID value used when collecting {@link NetworkStatsHistory} for
88 * tethering traffic.
89 *
90 * @hide
91 */
junyulai55041a42019-11-15 17:15:01 +080092 public static final int UID_TETHERING = NetworkStats.UID_TETHERING;
Jeff Sharkey987f5ff2011-09-16 01:52:49 -070093
94 /**
Chalard Jean8a93ab82019-04-09 11:16:56 +090095 * Tag values in this range are reserved for the network stack. The network stack is
96 * running as UID {@link android.os.Process.NETWORK_STACK_UID} when in the mainline
97 * module separate process, and as the system UID otherwise.
98 */
99 /** @hide */
100 @SystemApi
101 public static final int TAG_NETWORK_STACK_RANGE_START = 0xFFFFFD00;
102 /** @hide */
103 @SystemApi
104 public static final int TAG_NETWORK_STACK_RANGE_END = 0xFFFFFEFF;
105
106 /**
107 * Tags between 0xFFFFFF00 and 0xFFFFFFFF are reserved and used internally by system services
108 * like DownloadManager when performing traffic on behalf of an application.
109 */
110 // Please note there is no enforcement of these constants, so do not rely on them to
111 // determine that the caller is a system caller.
112 /** @hide */
113 @SystemApi
114 public static final int TAG_SYSTEM_IMPERSONATION_RANGE_START = 0xFFFFFF00;
115 /** @hide */
116 @SystemApi
117 public static final int TAG_SYSTEM_IMPERSONATION_RANGE_END = 0xFFFFFF0F;
118
119 /**
120 * Tag values between these ranges are reserved for the network stack to do traffic
121 * on behalf of applications. It is a subrange of the range above.
122 */
123 /** @hide */
124 @SystemApi
125 public static final int TAG_NETWORK_STACK_IMPERSONATION_RANGE_START = 0xFFFFFF80;
126 /** @hide */
127 @SystemApi
128 public static final int TAG_NETWORK_STACK_IMPERSONATION_RANGE_END = 0xFFFFFF8F;
129
130 /**
Jeff Sharkey92790062011-06-24 17:05:24 -0700131 * Default tag value for {@link DownloadManager} traffic.
132 *
133 * @hide
134 */
Jeff Sharkey987f5ff2011-09-16 01:52:49 -0700135 public static final int TAG_SYSTEM_DOWNLOAD = 0xFFFFFF01;
Jeff Sharkey92790062011-06-24 17:05:24 -0700136
137 /**
138 * Default tag value for {@link MediaPlayer} traffic.
139 *
140 * @hide
141 */
Jeff Sharkey987f5ff2011-09-16 01:52:49 -0700142 public static final int TAG_SYSTEM_MEDIA = 0xFFFFFF02;
Jeff Sharkey92790062011-06-24 17:05:24 -0700143
144 /**
Christopher Tatec1c71fd2015-11-10 10:49:20 -0800145 * Default tag value for {@link BackupManager} backup traffic; that is,
146 * traffic from the device to the storage backend.
Jeff Sharkey92790062011-06-24 17:05:24 -0700147 *
148 * @hide
149 */
Jeff Sharkey987f5ff2011-09-16 01:52:49 -0700150 public static final int TAG_SYSTEM_BACKUP = 0xFFFFFF03;
Jeff Sharkey92790062011-06-24 17:05:24 -0700151
Christopher Tatec1c71fd2015-11-10 10:49:20 -0800152 /**
153 * Default tag value for {@link BackupManager} restore traffic; that is,
154 * app data retrieved from the storage backend at install time.
155 *
156 * @hide
157 */
158 public static final int TAG_SYSTEM_RESTORE = 0xFFFFFF04;
159
Jeff Sharkey66dca172016-11-21 12:14:50 -0700160 /**
Jeff Sharkeyb1f97ac2017-08-11 15:04:12 -0600161 * Default tag value for code (typically APKs) downloaded by an app store on
162 * behalf of the app, such as updates.
Jeff Sharkey66dca172016-11-21 12:14:50 -0700163 *
164 * @hide
165 */
Jeff Sharkeyb1f97ac2017-08-11 15:04:12 -0600166 public static final int TAG_SYSTEM_APP = 0xFFFFFF05;
Jeff Sharkey8af5ad12017-06-26 19:50:41 -0600167
Chalard Jean8a93ab82019-04-09 11:16:56 +0900168 // TODO : remove this constant when Wifi code is updated
Jeff Sharkey8af5ad12017-06-26 19:50:41 -0600169 /** @hide */
Jeff Sharkey8af5ad12017-06-26 19:50:41 -0600170 public static final int TAG_SYSTEM_PROBE = 0xFFFFFF42;
Jeff Sharkey66dca172016-11-21 12:14:50 -0700171
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700172 private static INetworkStatsService sStatsService;
173
Chalard Jean3cfb4992019-04-09 15:46:21 +0900174 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700175 private synchronized static INetworkStatsService getStatsService() {
176 if (sStatsService == null) {
Junyu Lai92d5b4c2022-01-19 08:33:21 +0000177 throw new IllegalStateException("TrafficStats not initialized, uid="
178 + Binder.getCallingUid());
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700179 }
180 return sStatsService;
181 }
182
Jeff Sharkey92790062011-06-24 17:05:24 -0700183 /**
Jeff Sharkey33936ac2011-05-17 14:55:15 -0700184 * Snapshot of {@link NetworkStats} when the currently active profiling
185 * session started, or {@code null} if no session active.
186 *
187 * @see #startDataProfiling(Context)
188 * @see #stopDataProfiling(Context)
189 */
190 private static NetworkStats sActiveProfilingStart;
191
192 private static Object sProfilingLock = new Object();
193
Benedict Wong083faee2017-12-03 19:42:36 -0800194 private static final String LOOPBACK_IFACE = "lo";
195
Jeff Sharkey33936ac2011-05-17 14:55:15 -0700196 /**
Junyu Lai92d5b4c2022-01-19 08:33:21 +0000197 * Initialization {@link TrafficStats} with the context, to
198 * allow {@link TrafficStats} to fetch the needed binder.
199 *
200 * @param context a long-lived context, such as the application context or system
201 * server context.
202 * @hide
203 */
204 @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
205 @SuppressLint("VisiblySynchronized")
206 public static synchronized void init(@NonNull final Context context) {
207 if (sStatsService != null) {
208 throw new IllegalStateException("TrafficStats is already initialized, uid="
209 + Binder.getCallingUid());
210 }
211 final NetworkStatsManager statsManager =
212 context.getSystemService(NetworkStatsManager.class);
213 sStatsService = statsManager.getBinder();
214 }
215
216 /**
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700217 * Set active tag to use when accounting {@link Socket} traffic originating
218 * from the current thread. Only one active tag per thread is supported.
219 * <p>
220 * Changes only take effect during subsequent calls to
221 * {@link #tagSocket(Socket)}.
Jeff Sharkey987f5ff2011-09-16 01:52:49 -0700222 * <p>
223 * Tags between {@code 0xFFFFFF00} and {@code 0xFFFFFFFF} are reserved and
224 * used internally by system services like {@link DownloadManager} when
225 * performing traffic on behalf of an application.
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700226 *
227 * @see #clearThreadStatsTag()
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700228 */
Jeff Sharkey92790062011-06-24 17:05:24 -0700229 public static void setThreadStatsTag(int tag) {
Jesse Wilsonb05f41c2011-06-28 19:06:31 -0700230 NetworkManagementSocketTagger.setThreadSocketStatsTag(tag);
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700231 }
232
Jeff Sharkey92790062011-06-24 17:05:24 -0700233 /**
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600234 * Set active tag to use when accounting {@link Socket} traffic originating
Jeff Sharkey289eac12017-01-19 11:55:54 -0700235 * from the current thread. Only one active tag per thread is supported.
236 * <p>
237 * Changes only take effect during subsequent calls to
238 * {@link #tagSocket(Socket)}.
239 * <p>
240 * Tags between {@code 0xFFFFFF00} and {@code 0xFFFFFFFF} are reserved and
241 * used internally by system services like {@link DownloadManager} when
242 * performing traffic on behalf of an application.
243 *
244 * @return the current tag for the calling thread, which can be used to
245 * restore any existing values after a nested operation is finished
246 */
247 public static int getAndSetThreadStatsTag(int tag) {
248 return NetworkManagementSocketTagger.setThreadSocketStatsTag(tag);
249 }
250
251 /**
252 * Set active tag to use when accounting {@link Socket} traffic originating
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600253 * from the current thread. The tag used internally is well-defined to
254 * distinguish all backup-related traffic.
255 *
Christopher Tate5a1878d2014-08-06 14:19:56 -0700256 * @hide
257 */
258 @SystemApi
259 public static void setThreadStatsTagBackup() {
260 setThreadStatsTag(TAG_SYSTEM_BACKUP);
261 }
262
263 /**
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600264 * Set active tag to use when accounting {@link Socket} traffic originating
265 * from the current thread. The tag used internally is well-defined to
266 * distinguish all restore-related traffic.
267 *
Christopher Tatec1c71fd2015-11-10 10:49:20 -0800268 * @hide
269 */
270 @SystemApi
271 public static void setThreadStatsTagRestore() {
272 setThreadStatsTag(TAG_SYSTEM_RESTORE);
273 }
274
275 /**
Jeff Sharkey8af5ad12017-06-26 19:50:41 -0600276 * Set active tag to use when accounting {@link Socket} traffic originating
277 * from the current thread. The tag used internally is well-defined to
Jeff Sharkeyb1f97ac2017-08-11 15:04:12 -0600278 * distinguish all code (typically APKs) downloaded by an app store on
279 * behalf of the app, such as updates.
Jeff Sharkey8af5ad12017-06-26 19:50:41 -0600280 *
281 * @hide
282 */
283 @SystemApi
Jeff Sharkeyb1f97ac2017-08-11 15:04:12 -0600284 public static void setThreadStatsTagApp() {
285 setThreadStatsTag(TAG_SYSTEM_APP);
Jeff Sharkey8af5ad12017-06-26 19:50:41 -0600286 }
287
288 /**
Junyu Laiab2c35e2022-01-18 02:46:23 +0000289 * Set active tag to use when accounting {@link Socket} traffic originating
290 * from the current thread. The tag used internally is well-defined to
291 * distinguish all download provider traffic.
292 *
293 * @hide
294 */
295 @SystemApi
296 public static void setThreadStatsTagDownload() {
297 setThreadStatsTag(TAG_SYSTEM_DOWNLOAD);
298 }
299
300 /**
Alon Albert2c295f02011-07-19 11:16:09 +0300301 * Get the active tag used when accounting {@link Socket} traffic originating
302 * from the current thread. Only one active tag per thread is supported.
303 * {@link #tagSocket(Socket)}.
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700304 *
305 * @see #setThreadStatsTag(int)
Alon Albert2c295f02011-07-19 11:16:09 +0300306 */
307 public static int getThreadStatsTag() {
308 return NetworkManagementSocketTagger.getThreadSocketStatsTag();
309 }
310
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700311 /**
312 * Clear any active tag set to account {@link Socket} traffic originating
313 * from the current thread.
314 *
315 * @see #setThreadStatsTag(int)
316 */
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700317 public static void clearThreadStatsTag() {
Jesse Wilsonb05f41c2011-06-28 19:06:31 -0700318 NetworkManagementSocketTagger.setThreadSocketStatsTag(-1);
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700319 }
320
321 /**
322 * Set specific UID to use when accounting {@link Socket} traffic
323 * originating from the current thread. Designed for use when performing an
Jeff Sharkey17a38752018-03-26 13:11:33 -0600324 * operation on behalf of another application, or when another application
325 * is performing operations on your behalf.
326 * <p>
327 * Any app can <em>accept</em> blame for traffic performed on a socket
328 * originally created by another app by calling this method with the
329 * {@link android.system.Os#getuid()} value. However, only apps holding the
330 * {@code android.Manifest.permission#UPDATE_DEVICE_STATS} permission may
331 * <em>assign</em> blame to another UIDs.
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700332 * <p>
333 * Changes only take effect during subsequent calls to
334 * {@link #tagSocket(Socket)}.
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700335 */
Aurimas Liutikas9de1e0e2020-11-12 18:29:11 -0800336 @SuppressLint("RequiresPermission")
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700337 public static void setThreadStatsUid(int uid) {
Jesse Wilsonb05f41c2011-06-28 19:06:31 -0700338 NetworkManagementSocketTagger.setThreadSocketStatsUid(uid);
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700339 }
340
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600341 /**
Jeff Sharkey17a38752018-03-26 13:11:33 -0600342 * Get the active UID used when accounting {@link Socket} traffic originating
343 * from the current thread. Only one active tag per thread is supported.
344 * {@link #tagSocket(Socket)}.
345 *
346 * @see #setThreadStatsUid(int)
347 */
348 public static int getThreadStatsUid() {
349 return NetworkManagementSocketTagger.getThreadSocketStatsUid();
350 }
351
352 /**
Jeff Sharkey1fb74312017-11-29 11:18:23 -0700353 * Set specific UID to use when accounting {@link Socket} traffic
354 * originating from the current thread as the calling UID. Designed for use
355 * when another application is performing operations on your behalf.
356 * <p>
357 * Changes only take effect during subsequent calls to
358 * {@link #tagSocket(Socket)}.
Jeff Sharkey17a38752018-03-26 13:11:33 -0600359 *
360 * @removed
361 * @deprecated use {@link #setThreadStatsUid(int)} instead.
Jeff Sharkey1fb74312017-11-29 11:18:23 -0700362 */
Jeff Sharkey17a38752018-03-26 13:11:33 -0600363 @Deprecated
Jeff Sharkey1fb74312017-11-29 11:18:23 -0700364 public static void setThreadStatsUidSelf() {
365 setThreadStatsUid(android.os.Process.myUid());
366 }
367
368 /**
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600369 * Clear any active UID set to account {@link Socket} traffic originating
370 * from the current thread.
371 *
372 * @see #setThreadStatsUid(int)
Jeff Sharkeyf7591592016-03-22 10:20:12 -0600373 */
Aurimas Liutikas9de1e0e2020-11-12 18:29:11 -0800374 @SuppressLint("RequiresPermission")
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700375 public static void clearThreadStatsUid() {
Jesse Wilsonb05f41c2011-06-28 19:06:31 -0700376 NetworkManagementSocketTagger.setThreadSocketStatsUid(-1);
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700377 }
378
379 /**
380 * Tag the given {@link Socket} with any statistics parameters active for
381 * the current thread. Subsequent calls always replace any existing
382 * parameters. When finished, call {@link #untagSocket(Socket)} to remove
383 * statistics parameters.
384 *
Jeff Sharkey92790062011-06-24 17:05:24 -0700385 * @see #setThreadStatsTag(int)
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700386 */
387 public static void tagSocket(Socket socket) throws SocketException {
Jesse Wilsonb05f41c2011-06-28 19:06:31 -0700388 SocketTagger.get().tag(socket);
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700389 }
390
391 /**
392 * Remove any statistics parameters from the given {@link Socket}.
koprivac134e242018-07-23 18:19:39 -0700393 * <p>
394 * In Android 8.1 (API level 27) and lower, a socket is automatically
395 * untagged when it's sent to another process using binder IPC with a
396 * {@code ParcelFileDescriptor} container. In Android 9.0 (API level 28)
397 * and higher, the socket tag is kept when the socket is sent to another
398 * process using binder IPC. You can mimic the previous behavior by
399 * calling {@code untagSocket()} before sending the socket to another
400 * process.
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700401 */
402 public static void untagSocket(Socket socket) throws SocketException {
Jesse Wilsonb05f41c2011-06-28 19:06:31 -0700403 SocketTagger.get().untag(socket);
Jeff Sharkeyb82cd3d2011-04-21 18:45:43 -0700404 }
405
406 /**
Jeff Sharkey7b124cb2015-12-04 15:21:52 -0700407 * Tag the given {@link DatagramSocket} with any statistics parameters
408 * active for the current thread. Subsequent calls always replace any
409 * existing parameters. When finished, call
410 * {@link #untagDatagramSocket(DatagramSocket)} to remove statistics
411 * parameters.
412 *
413 * @see #setThreadStatsTag(int)
Jeff Sharkey7b124cb2015-12-04 15:21:52 -0700414 */
415 public static void tagDatagramSocket(DatagramSocket socket) throws SocketException {
416 SocketTagger.get().tag(socket);
417 }
418
419 /**
420 * Remove any statistics parameters from the given {@link DatagramSocket}.
421 */
422 public static void untagDatagramSocket(DatagramSocket socket) throws SocketException {
423 SocketTagger.get().untag(socket);
424 }
425
426 /**
Jeff Sharkey1fb74312017-11-29 11:18:23 -0700427 * Tag the given {@link FileDescriptor} socket with any statistics
428 * parameters active for the current thread. Subsequent calls always replace
429 * any existing parameters. When finished, call
430 * {@link #untagFileDescriptor(FileDescriptor)} to remove statistics
431 * parameters.
432 *
433 * @see #setThreadStatsTag(int)
434 */
435 public static void tagFileDescriptor(FileDescriptor fd) throws IOException {
436 SocketTagger.get().tag(fd);
437 }
438
439 /**
440 * Remove any statistics parameters from the given {@link FileDescriptor}
441 * socket.
442 */
443 public static void untagFileDescriptor(FileDescriptor fd) throws IOException {
444 SocketTagger.get().untag(fd);
445 }
446
447 /**
Jeff Sharkey33936ac2011-05-17 14:55:15 -0700448 * Start profiling data usage for current UID. Only one profiling session
449 * can be active at a time.
450 *
451 * @hide
452 */
453 public static void startDataProfiling(Context context) {
454 synchronized (sProfilingLock) {
455 if (sActiveProfilingStart != null) {
456 throw new IllegalStateException("already profiling data");
457 }
458
459 // take snapshot in time; we calculate delta later
Jeff Sharkey7407e092011-07-19 23:47:12 -0700460 sActiveProfilingStart = getDataLayerSnapshotForUid(context);
Jeff Sharkey33936ac2011-05-17 14:55:15 -0700461 }
462 }
463
464 /**
465 * Stop profiling data usage for current UID.
466 *
467 * @return Detailed {@link NetworkStats} of data that occurred since last
468 * {@link #startDataProfiling(Context)} call.
469 * @hide
470 */
471 public static NetworkStats stopDataProfiling(Context context) {
472 synchronized (sProfilingLock) {
473 if (sActiveProfilingStart == null) {
474 throw new IllegalStateException("not profiling data");
475 }
476
Jeff Sharkeyef7bded2012-01-10 17:24:44 -0800477 // subtract starting values and return delta
478 final NetworkStats profilingStop = getDataLayerSnapshotForUid(context);
479 final NetworkStats profilingDelta = NetworkStats.subtract(
Jeff Sharkeybfe82682012-01-11 18:38:16 -0800480 profilingStop, sActiveProfilingStart, null, null);
Jeff Sharkeyef7bded2012-01-10 17:24:44 -0800481 sActiveProfilingStart = null;
482 return profilingDelta;
Jeff Sharkey33936ac2011-05-17 14:55:15 -0700483 }
484 }
485
486 /**
Jeff Sharkey60ca0232011-08-24 15:42:09 -0700487 * Increment count of network operations performed under the accounting tag
488 * currently active on the calling thread. This can be used to derive
489 * bytes-per-operation.
490 *
491 * @param operationCount Number of operations to increment count by.
492 */
493 public static void incrementOperationCount(int operationCount) {
494 final int tag = getThreadStatsTag();
495 incrementOperationCount(tag, operationCount);
496 }
497
498 /**
Jeff Sharkey7407e092011-07-19 23:47:12 -0700499 * Increment count of network operations performed under the given
500 * accounting tag. This can be used to derive bytes-per-operation.
501 *
502 * @param tag Accounting tag used in {@link #setThreadStatsTag(int)}.
503 * @param operationCount Number of operations to increment count by.
504 */
505 public static void incrementOperationCount(int tag, int operationCount) {
Jeff Sharkey7407e092011-07-19 23:47:12 -0700506 final int uid = android.os.Process.myUid();
507 try {
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700508 getStatsService().incrementOperationCount(uid, tag, operationCount);
Jeff Sharkey7407e092011-07-19 23:47:12 -0700509 } catch (RemoteException e) {
Jeff Sharkeybc08d072016-02-26 13:03:01 -0700510 throw e.rethrowFromSystemServer();
Jeff Sharkey7407e092011-07-19 23:47:12 -0700511 }
512 }
513
Jeff Sharkey920d9042012-04-06 11:12:08 -0700514 /** {@hide} */
515 public static void closeQuietly(INetworkStatsSession session) {
516 // TODO: move to NetworkStatsService once it exists
517 if (session != null) {
518 try {
519 session.close();
520 } catch (RuntimeException rethrown) {
521 throw rethrown;
522 } catch (Exception ignored) {
523 }
524 }
525 }
526
Chenbo Feng905f0342018-01-25 11:43:52 -0800527 private static long addIfSupported(long stat) {
528 return (stat == UNSUPPORTED) ? 0 : stat;
529 }
530
Jeff Sharkey7407e092011-07-19 23:47:12 -0700531 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700532 * Return number of packets transmitted across mobile networks since device
533 * boot. Counts packets across all mobile network interfaces, and always
534 * increases monotonically since device boot. Statistics are measured at the
535 * network layer, so they include both TCP and UDP usage.
536 * <p>
537 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
538 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800539 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700540 public static long getMobileTxPackets() {
541 long total = 0;
542 for (String iface : getMobileIfaces()) {
Chenbo Feng905f0342018-01-25 11:43:52 -0800543 total += addIfSupported(getTxPackets(iface));
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700544 }
545 return total;
546 }
Ken Shirriffae521152009-12-07 15:56:05 -0800547
548 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700549 * Return number of packets received across mobile networks since device
550 * boot. Counts packets across all mobile network interfaces, and always
551 * increases monotonically since device boot. Statistics are measured at the
552 * network layer, so they include both TCP and UDP usage.
553 * <p>
554 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
555 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800556 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700557 public static long getMobileRxPackets() {
558 long total = 0;
559 for (String iface : getMobileIfaces()) {
Chenbo Feng905f0342018-01-25 11:43:52 -0800560 total += addIfSupported(getRxPackets(iface));
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700561 }
562 return total;
563 }
Ken Shirriffae521152009-12-07 15:56:05 -0800564
565 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700566 * Return number of bytes transmitted across mobile networks since device
567 * boot. Counts packets across all mobile network interfaces, and always
568 * increases monotonically since device boot. Statistics are measured at the
569 * network layer, so they include both TCP and UDP usage.
570 * <p>
571 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
572 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800573 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700574 public static long getMobileTxBytes() {
575 long total = 0;
576 for (String iface : getMobileIfaces()) {
Chenbo Feng905f0342018-01-25 11:43:52 -0800577 total += addIfSupported(getTxBytes(iface));
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700578 }
579 return total;
580 }
Ken Shirriffae521152009-12-07 15:56:05 -0800581
582 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700583 * Return number of bytes received across mobile networks since device boot.
584 * Counts packets across all mobile network interfaces, and always increases
585 * monotonically since device boot. Statistics are measured at the network
586 * layer, so they include both TCP and UDP usage.
587 * <p>
588 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
589 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800590 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700591 public static long getMobileRxBytes() {
592 long total = 0;
593 for (String iface : getMobileIfaces()) {
Chenbo Feng905f0342018-01-25 11:43:52 -0800594 total += addIfSupported(getRxBytes(iface));
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700595 }
596 return total;
597 }
Ken Shirriffae521152009-12-07 15:56:05 -0800598
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800599 /** {@hide} */
Mathew Inwoodfe2fed72020-11-04 09:29:36 +0000600 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800601 public static long getMobileTcpRxPackets() {
602 long total = 0;
603 for (String iface : getMobileIfaces()) {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800604 long stat = UNSUPPORTED;
605 try {
606 stat = getStatsService().getIfaceStats(iface, TYPE_TCP_RX_PACKETS);
607 } catch (RemoteException e) {
608 throw e.rethrowFromSystemServer();
609 }
Chenbo Feng905f0342018-01-25 11:43:52 -0800610 total += addIfSupported(stat);
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800611 }
612 return total;
613 }
614
615 /** {@hide} */
Mathew Inwoodfe2fed72020-11-04 09:29:36 +0000616 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800617 public static long getMobileTcpTxPackets() {
618 long total = 0;
619 for (String iface : getMobileIfaces()) {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800620 long stat = UNSUPPORTED;
621 try {
622 stat = getStatsService().getIfaceStats(iface, TYPE_TCP_TX_PACKETS);
623 } catch (RemoteException e) {
624 throw e.rethrowFromSystemServer();
625 }
Chenbo Feng905f0342018-01-25 11:43:52 -0800626 total += addIfSupported(stat);
Jeff Sharkey9e766ac2013-02-05 21:32:33 -0800627 }
628 return total;
629 }
630
Aaron Huang443651d2019-09-27 22:31:22 +0800631 /**
junyulai3154d512020-09-29 14:19:24 +0800632 * Return the number of packets transmitted on the specified interface since the interface
633 * was created. Statistics are measured at the network layer, so both TCP and
Aaron Huang443651d2019-09-27 22:31:22 +0800634 * UDP usage are included.
635 *
junyulai3154d512020-09-29 14:19:24 +0800636 * Note that the returned values are partial statistics that do not count data from several
637 * sources and do not apply several adjustments that are necessary for correctness, such
638 * as adjusting for VPN apps, IPv6-in-IPv4 translation, etc. These values can be used to
639 * determine whether traffic is being transferred on the specific interface but are not a
640 * substitute for the more accurate statistics provided by the {@link NetworkStatsManager}
641 * APIs.
642 *
Aaron Huang443651d2019-09-27 22:31:22 +0800643 * @param iface The name of the interface.
644 * @return The number of transmitted packets.
645 */
646 public static long getTxPackets(@NonNull String iface) {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800647 try {
648 return getStatsService().getIfaceStats(iface, TYPE_TX_PACKETS);
649 } catch (RemoteException e) {
650 throw e.rethrowFromSystemServer();
651 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700652 }
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800653
Aaron Huang443651d2019-09-27 22:31:22 +0800654 /**
junyulai3154d512020-09-29 14:19:24 +0800655 * Return the number of packets received on the specified interface since the interface was
656 * created. Statistics are measured at the network layer, so both TCP
Aaron Huang443651d2019-09-27 22:31:22 +0800657 * and UDP usage are included.
658 *
junyulai3154d512020-09-29 14:19:24 +0800659 * Note that the returned values are partial statistics that do not count data from several
660 * sources and do not apply several adjustments that are necessary for correctness, such
661 * as adjusting for VPN apps, IPv6-in-IPv4 translation, etc. These values can be used to
662 * determine whether traffic is being transferred on the specific interface but are not a
663 * substitute for the more accurate statistics provided by the {@link NetworkStatsManager}
664 * APIs.
665 *
Aaron Huang443651d2019-09-27 22:31:22 +0800666 * @param iface The name of the interface.
667 * @return The number of received packets.
668 */
669 public static long getRxPackets(@NonNull String iface) {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800670 try {
671 return getStatsService().getIfaceStats(iface, TYPE_RX_PACKETS);
672 } catch (RemoteException e) {
673 throw e.rethrowFromSystemServer();
674 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700675 }
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800676
junyulai3154d512020-09-29 14:19:24 +0800677 /**
678 * Return the number of bytes transmitted on the specified interface since the interface
679 * was created. Statistics are measured at the network layer, so both TCP and
680 * UDP usage are included.
681 *
682 * Note that the returned values are partial statistics that do not count data from several
683 * sources and do not apply several adjustments that are necessary for correctness, such
684 * as adjusting for VPN apps, IPv6-in-IPv4 translation, etc. These values can be used to
685 * determine whether traffic is being transferred on the specific interface but are not a
686 * substitute for the more accurate statistics provided by the {@link NetworkStatsManager}
687 * APIs.
688 *
689 * @param iface The name of the interface.
690 * @return The number of transmitted bytes.
691 */
692 public static long getTxBytes(@NonNull String iface) {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800693 try {
694 return getStatsService().getIfaceStats(iface, TYPE_TX_BYTES);
695 } catch (RemoteException e) {
696 throw e.rethrowFromSystemServer();
697 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700698 }
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800699
junyulai3154d512020-09-29 14:19:24 +0800700 /**
701 * Return the number of bytes received on the specified interface since the interface
702 * was created. Statistics are measured at the network layer, so both TCP
703 * and UDP usage are included.
704 *
705 * Note that the returned values are partial statistics that do not count data from several
706 * sources and do not apply several adjustments that are necessary for correctness, such
707 * as adjusting for VPN apps, IPv6-in-IPv4 translation, etc. These values can be used to
708 * determine whether traffic is being transferred on the specific interface but are not a
709 * substitute for the more accurate statistics provided by the {@link NetworkStatsManager}
710 * APIs.
711 *
712 * @param iface The name of the interface.
713 * @return The number of received bytes.
714 */
715 public static long getRxBytes(@NonNull String iface) {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800716 try {
717 return getStatsService().getIfaceStats(iface, TYPE_RX_BYTES);
718 } catch (RemoteException e) {
719 throw e.rethrowFromSystemServer();
720 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700721 }
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800722
Benedict Wong083faee2017-12-03 19:42:36 -0800723 /** {@hide} */
724 @TestApi
725 public static long getLoopbackTxPackets() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800726 try {
727 return getStatsService().getIfaceStats(LOOPBACK_IFACE, TYPE_TX_PACKETS);
728 } catch (RemoteException e) {
729 throw e.rethrowFromSystemServer();
730 }
Benedict Wong083faee2017-12-03 19:42:36 -0800731 }
732
733 /** {@hide} */
734 @TestApi
735 public static long getLoopbackRxPackets() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800736 try {
737 return getStatsService().getIfaceStats(LOOPBACK_IFACE, TYPE_RX_PACKETS);
738 } catch (RemoteException e) {
739 throw e.rethrowFromSystemServer();
740 }
Benedict Wong083faee2017-12-03 19:42:36 -0800741 }
742
743 /** {@hide} */
744 @TestApi
745 public static long getLoopbackTxBytes() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800746 try {
747 return getStatsService().getIfaceStats(LOOPBACK_IFACE, TYPE_TX_BYTES);
748 } catch (RemoteException e) {
749 throw e.rethrowFromSystemServer();
750 }
Benedict Wong083faee2017-12-03 19:42:36 -0800751 }
752
753 /** {@hide} */
754 @TestApi
755 public static long getLoopbackRxBytes() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800756 try {
757 return getStatsService().getIfaceStats(LOOPBACK_IFACE, TYPE_RX_BYTES);
758 } catch (RemoteException e) {
759 throw e.rethrowFromSystemServer();
760 }
Benedict Wong083faee2017-12-03 19:42:36 -0800761 }
762
Irfan Sheriff042f4e12011-02-15 19:30:27 -0800763 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700764 * Return number of packets transmitted since device boot. Counts packets
765 * across all network interfaces, and always increases monotonically since
766 * device boot. Statistics are measured at the network layer, so they
767 * include both TCP and UDP usage.
768 * <p>
769 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
770 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800771 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700772 public static long getTotalTxPackets() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800773 try {
774 return getStatsService().getTotalStats(TYPE_TX_PACKETS);
775 } catch (RemoteException e) {
776 throw e.rethrowFromSystemServer();
777 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700778 }
Ken Shirriffae521152009-12-07 15:56:05 -0800779
780 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700781 * Return number of packets received since device boot. Counts packets
782 * across all network interfaces, and always increases monotonically since
783 * device boot. Statistics are measured at the network layer, so they
784 * include both TCP and UDP usage.
785 * <p>
786 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
787 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800788 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700789 public static long getTotalRxPackets() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800790 try {
791 return getStatsService().getTotalStats(TYPE_RX_PACKETS);
792 } catch (RemoteException e) {
793 throw e.rethrowFromSystemServer();
794 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700795 }
Ken Shirriffae521152009-12-07 15:56:05 -0800796
797 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700798 * Return number of bytes transmitted since device boot. Counts packets
799 * across all network interfaces, and always increases monotonically since
800 * device boot. Statistics are measured at the network layer, so they
801 * include both TCP and UDP usage.
802 * <p>
803 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
804 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800805 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700806 public static long getTotalTxBytes() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800807 try {
808 return getStatsService().getTotalStats(TYPE_TX_BYTES);
809 } catch (RemoteException e) {
810 throw e.rethrowFromSystemServer();
811 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700812 }
Ken Shirriffae521152009-12-07 15:56:05 -0800813
814 /**
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -0700815 * Return number of bytes received since device boot. Counts packets across
816 * all network interfaces, and always increases monotonically since device
817 * boot. Statistics are measured at the network layer, so they include both
818 * TCP and UDP usage.
819 * <p>
820 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
821 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
Ken Shirriffae521152009-12-07 15:56:05 -0800822 */
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700823 public static long getTotalRxBytes() {
Chenbo Fengaa7ba312017-11-14 17:54:17 -0800824 try {
825 return getStatsService().getTotalStats(TYPE_RX_BYTES);
826 } catch (RemoteException e) {
827 throw e.rethrowFromSystemServer();
828 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -0700829 }
Ken Shirriffae521152009-12-07 15:56:05 -0800830
831 /**
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800832 * Return number of bytes transmitted by the given UID since device boot.
833 * Counts packets across all network interfaces, and always increases
834 * monotonically since device boot. Statistics are measured at the network
835 * layer, so they include both TCP and UDP usage.
836 * <p>
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700837 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
838 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
839 * <p>
840 * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
841 * report traffic statistics for the calling UID. It will return
842 * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
843 * historical network statistics belonging to other UIDs, use
844 * {@link NetworkStatsManager}.
Ken Shirriffae521152009-12-07 15:56:05 -0800845 *
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800846 * @see android.os.Process#myUid()
847 * @see android.content.pm.ApplicationInfo#uid
Ken Shirriffae521152009-12-07 15:56:05 -0800848 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800849 public static long getUidTxBytes(int uid) {
Chenbo Fengd80a6ed2019-06-17 16:22:28 -0700850 try {
851 return getStatsService().getUidStats(uid, TYPE_TX_BYTES);
852 } catch (RemoteException e) {
853 throw e.rethrowFromSystemServer();
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700854 }
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800855 }
Ken Shirriffae521152009-12-07 15:56:05 -0800856
857 /**
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800858 * Return number of bytes received by the given UID since device boot.
859 * Counts packets across all network interfaces, and always increases
860 * monotonically since device boot. Statistics are measured at the network
861 * layer, so they include both TCP and UDP usage.
862 * <p>
Dianne Hackborne9d72072013-02-25 15:55:37 -0800863 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800864 * {@link #UNSUPPORTED} on devices where statistics aren't available.
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700865 * <p>
866 * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
867 * report traffic statistics for the calling UID. It will return
868 * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
869 * historical network statistics belonging to other UIDs, use
870 * {@link NetworkStatsManager}.
Ken Shirriffae521152009-12-07 15:56:05 -0800871 *
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800872 * @see android.os.Process#myUid()
873 * @see android.content.pm.ApplicationInfo#uid
Ken Shirriffae521152009-12-07 15:56:05 -0800874 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800875 public static long getUidRxBytes(int uid) {
Chenbo Fengd80a6ed2019-06-17 16:22:28 -0700876 try {
877 return getStatsService().getUidStats(uid, TYPE_RX_BYTES);
878 } catch (RemoteException e) {
879 throw e.rethrowFromSystemServer();
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700880 }
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800881 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800882
883 /**
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800884 * Return number of packets transmitted by the given UID since device boot.
885 * Counts packets across all network interfaces, and always increases
886 * monotonically since device boot. Statistics are measured at the network
887 * layer, so they include both TCP and UDP usage.
888 * <p>
Dianne Hackborne9d72072013-02-25 15:55:37 -0800889 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800890 * {@link #UNSUPPORTED} on devices where statistics aren't available.
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700891 * <p>
892 * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
893 * report traffic statistics for the calling UID. It will return
894 * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
895 * historical network statistics belonging to other UIDs, use
896 * {@link NetworkStatsManager}.
Ashish Sharmadf852d82011-01-27 15:52:38 -0800897 *
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800898 * @see android.os.Process#myUid()
899 * @see android.content.pm.ApplicationInfo#uid
Ashish Sharmadf852d82011-01-27 15:52:38 -0800900 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800901 public static long getUidTxPackets(int uid) {
Chenbo Fengd80a6ed2019-06-17 16:22:28 -0700902 try {
903 return getStatsService().getUidStats(uid, TYPE_TX_PACKETS);
904 } catch (RemoteException e) {
905 throw e.rethrowFromSystemServer();
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700906 }
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800907 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800908
909 /**
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800910 * Return number of packets received by the given UID since device boot.
911 * Counts packets across all network interfaces, and always increases
912 * monotonically since device boot. Statistics are measured at the network
913 * layer, so they include both TCP and UDP usage.
914 * <p>
Dianne Hackborne9d72072013-02-25 15:55:37 -0800915 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800916 * {@link #UNSUPPORTED} on devices where statistics aren't available.
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700917 * <p>
918 * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
919 * report traffic statistics for the calling UID. It will return
920 * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
921 * historical network statistics belonging to other UIDs, use
922 * {@link NetworkStatsManager}.
Ashish Sharmadf852d82011-01-27 15:52:38 -0800923 *
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800924 * @see android.os.Process#myUid()
925 * @see android.content.pm.ApplicationInfo#uid
Ashish Sharmadf852d82011-01-27 15:52:38 -0800926 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800927 public static long getUidRxPackets(int uid) {
Chenbo Fengd80a6ed2019-06-17 16:22:28 -0700928 try {
929 return getStatsService().getUidStats(uid, TYPE_RX_PACKETS);
930 } catch (RemoteException e) {
931 throw e.rethrowFromSystemServer();
Jeff Sharkey27c8a072016-03-09 16:40:15 -0700932 }
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800933 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800934
935 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -0800936 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800937 * transport layer statistics are no longer available, and will
938 * always return {@link #UNSUPPORTED}.
939 * @see #getUidTxBytes(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -0800940 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800941 @Deprecated
942 public static long getUidTcpTxBytes(int uid) {
943 return UNSUPPORTED;
944 }
Ashish Sharmadf852d82011-01-27 15:52:38 -0800945
946 /**
Dianne Hackborne9d72072013-02-25 15:55:37 -0800947 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800948 * transport layer statistics are no longer available, and will
949 * always return {@link #UNSUPPORTED}.
950 * @see #getUidRxBytes(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -0800951 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800952 @Deprecated
953 public static long getUidTcpRxBytes(int uid) {
954 return UNSUPPORTED;
955 }
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 getUidUdpTxBytes(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 getUidUdpRxBytes(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 #getUidTxPackets(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -0800984 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800985 @Deprecated
986 public static long getUidTcpTxSegments(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 #getUidRxPackets(int)
Ashish Sharmadf852d82011-01-27 15:52:38 -0800995 */
Jeff Sharkey5fee2c92013-01-15 17:25:09 -0800996 @Deprecated
997 public static long getUidTcpRxSegments(int uid) {
998 return UNSUPPORTED;
999 }
Ashish Sharmadf852d82011-01-27 15:52:38 -08001000
Ashish Sharmadf852d82011-01-27 15:52:38 -08001001 /**
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 getUidUdpTxPackets(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 getUidUdpRxPackets(int uid) {
1020 return UNSUPPORTED;
1021 }
Jeff Sharkey33936ac2011-05-17 14:55:15 -07001022
1023 /**
1024 * Return detailed {@link NetworkStats} for the current UID. Requires no
1025 * special permission.
1026 */
Jeff Sharkey7407e092011-07-19 23:47:12 -07001027 private static NetworkStats getDataLayerSnapshotForUid(Context context) {
Jeff Sharkey39fb9cd2013-03-26 13:46:05 -07001028 // TODO: take snapshot locally, since proc file is now visible
Jeff Sharkey33936ac2011-05-17 14:55:15 -07001029 final int uid = android.os.Process.myUid();
1030 try {
Jeff Sharkey8308b9b2012-04-10 19:48:07 -07001031 return getStatsService().getDataLayerSnapshotForUid(uid);
Jeff Sharkey33936ac2011-05-17 14:55:15 -07001032 } catch (RemoteException e) {
Jeff Sharkeybc08d072016-02-26 13:03:01 -07001033 throw e.rethrowFromSystemServer();
Jeff Sharkey33936ac2011-05-17 14:55:15 -07001034 }
1035 }
Jeff Sharkey8308b9b2012-04-10 19:48:07 -07001036
1037 /**
1038 * Return set of any ifaces associated with mobile networks since boot.
1039 * Interfaces are never removed from this list, so counters should always be
1040 * monotonic.
1041 */
Chalard Jean3cfb4992019-04-09 15:46:21 +09001042 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
Jeff Sharkey8308b9b2012-04-10 19:48:07 -07001043 private static String[] getMobileIfaces() {
1044 try {
1045 return getStatsService().getMobileIfaces();
1046 } catch (RemoteException e) {
Jeff Sharkeybc08d072016-02-26 13:03:01 -07001047 throw e.rethrowFromSystemServer();
Jeff Sharkey8308b9b2012-04-10 19:48:07 -07001048 }
1049 }
1050
junyulaiea236322020-10-06 11:59:56 +08001051 // NOTE: keep these in sync with {@code com_android_server_net_NetworkStatsService.cpp}.
1052 /** {@hide} */
1053 public static final int TYPE_RX_BYTES = 0;
1054 /** {@hide} */
1055 public static final int TYPE_RX_PACKETS = 1;
1056 /** {@hide} */
1057 public static final int TYPE_TX_BYTES = 2;
1058 /** {@hide} */
1059 public static final int TYPE_TX_PACKETS = 3;
1060 /** {@hide} */
1061 public static final int TYPE_TCP_RX_PACKETS = 4;
1062 /** {@hide} */
1063 public static final int TYPE_TCP_TX_PACKETS = 5;
Ken Shirriffae521152009-12-07 15:56:05 -08001064}