2 * Copyright (C) 2007 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 import android.annotation.SystemApi;
20 import android.app.DownloadManager;
21 import android.app.backup.BackupManager;
22 import android.app.usage.NetworkStatsManager;
23 import android.content.Context;
24 import android.media.MediaPlayer;
25 import android.os.RemoteException;
26 import android.os.ServiceManager;
28 import com.android.server.NetworkManagementSocketTagger;
30 import dalvik.system.SocketTagger;
32 import java.net.DatagramSocket;
33 import java.net.Socket;
34 import java.net.SocketException;
37 * Class that provides network traffic statistics. These statistics include
38 * bytes transmitted and received and network packets transmitted and received,
39 * over all interfaces, over the mobile interface, and on a per-UID basis.
41 * These statistics may not be available on all platforms. If the statistics are
42 * not supported by this device, {@link #UNSUPPORTED} will be returned.
44 * Note that the statistics returned by this class reset and start from zero
45 * after every reboot. To access more robust historical network statistics data,
46 * use {@link NetworkStatsManager} instead.
48 public class TrafficStats {
50 * The return value to indicate that the device does not support the statistic.
52 public final static int UNSUPPORTED = -1;
55 public static final long KB_IN_BYTES = 1024;
57 public static final long MB_IN_BYTES = KB_IN_BYTES * 1024;
59 public static final long GB_IN_BYTES = MB_IN_BYTES * 1024;
61 public static final long TB_IN_BYTES = GB_IN_BYTES * 1024;
63 public static final long PB_IN_BYTES = TB_IN_BYTES * 1024;
66 * Special UID value used when collecting {@link NetworkStatsHistory} for
67 * removed applications.
71 public static final int UID_REMOVED = -4;
74 * Special UID value used when collecting {@link NetworkStatsHistory} for
79 public static final int UID_TETHERING = -5;
82 * Default tag value for {@link DownloadManager} traffic.
86 public static final int TAG_SYSTEM_DOWNLOAD = 0xFFFFFF01;
89 * Default tag value for {@link MediaPlayer} traffic.
93 public static final int TAG_SYSTEM_MEDIA = 0xFFFFFF02;
96 * Default tag value for {@link BackupManager} backup traffic; that is,
97 * traffic from the device to the storage backend.
101 public static final int TAG_SYSTEM_BACKUP = 0xFFFFFF03;
104 * Default tag value for {@link BackupManager} restore traffic; that is,
105 * app data retrieved from the storage backend at install time.
109 public static final int TAG_SYSTEM_RESTORE = 0xFFFFFF04;
111 private static INetworkStatsService sStatsService;
113 private synchronized static INetworkStatsService getStatsService() {
114 if (sStatsService == null) {
115 sStatsService = INetworkStatsService.Stub.asInterface(
116 ServiceManager.getService(Context.NETWORK_STATS_SERVICE));
118 return sStatsService;
122 * Snapshot of {@link NetworkStats} when the currently active profiling
123 * session started, or {@code null} if no session active.
125 * @see #startDataProfiling(Context)
126 * @see #stopDataProfiling(Context)
128 private static NetworkStats sActiveProfilingStart;
130 private static Object sProfilingLock = new Object();
133 * Set active tag to use when accounting {@link Socket} traffic originating
134 * from the current thread. Only one active tag per thread is supported.
136 * Changes only take effect during subsequent calls to
137 * {@link #tagSocket(Socket)}.
139 * Tags between {@code 0xFFFFFF00} and {@code 0xFFFFFFFF} are reserved and
140 * used internally by system services like {@link DownloadManager} when
141 * performing traffic on behalf of an application.
143 * @see #clearThreadStatsTag()
145 public static void setThreadStatsTag(int tag) {
146 NetworkManagementSocketTagger.setThreadSocketStatsTag(tag);
150 * Set active tag to use when accounting {@link Socket} traffic originating
151 * from the current thread. The tag used internally is well-defined to
152 * distinguish all backup-related traffic.
157 public static void setThreadStatsTagBackup() {
158 setThreadStatsTag(TAG_SYSTEM_BACKUP);
162 * Set active tag to use when accounting {@link Socket} traffic originating
163 * from the current thread. The tag used internally is well-defined to
164 * distinguish all restore-related traffic.
169 public static void setThreadStatsTagRestore() {
170 setThreadStatsTag(TAG_SYSTEM_RESTORE);
174 * Get the active tag used when accounting {@link Socket} traffic originating
175 * from the current thread. Only one active tag per thread is supported.
176 * {@link #tagSocket(Socket)}.
178 * @see #setThreadStatsTag(int)
180 public static int getThreadStatsTag() {
181 return NetworkManagementSocketTagger.getThreadSocketStatsTag();
185 * Clear any active tag set to account {@link Socket} traffic originating
186 * from the current thread.
188 * @see #setThreadStatsTag(int)
190 public static void clearThreadStatsTag() {
191 NetworkManagementSocketTagger.setThreadSocketStatsTag(-1);
195 * Set specific UID to use when accounting {@link Socket} traffic
196 * originating from the current thread. Designed for use when performing an
197 * operation on behalf of another application.
199 * Changes only take effect during subsequent calls to
200 * {@link #tagSocket(Socket)}.
202 * To take effect, caller must hold
203 * {@link android.Manifest.permission#UPDATE_DEVICE_STATS} permission.
208 public static void setThreadStatsUid(int uid) {
209 NetworkManagementSocketTagger.setThreadSocketStatsUid(uid);
213 * Clear any active UID set to account {@link Socket} traffic originating
214 * from the current thread.
216 * @see #setThreadStatsUid(int)
220 public static void clearThreadStatsUid() {
221 NetworkManagementSocketTagger.setThreadSocketStatsUid(-1);
225 * Tag the given {@link Socket} with any statistics parameters active for
226 * the current thread. Subsequent calls always replace any existing
227 * parameters. When finished, call {@link #untagSocket(Socket)} to remove
228 * statistics parameters.
230 * @see #setThreadStatsTag(int)
232 public static void tagSocket(Socket socket) throws SocketException {
233 SocketTagger.get().tag(socket);
237 * Remove any statistics parameters from the given {@link Socket}.
239 public static void untagSocket(Socket socket) throws SocketException {
240 SocketTagger.get().untag(socket);
244 * Tag the given {@link DatagramSocket} with any statistics parameters
245 * active for the current thread. Subsequent calls always replace any
246 * existing parameters. When finished, call
247 * {@link #untagDatagramSocket(DatagramSocket)} to remove statistics
250 * @see #setThreadStatsTag(int)
252 public static void tagDatagramSocket(DatagramSocket socket) throws SocketException {
253 SocketTagger.get().tag(socket);
257 * Remove any statistics parameters from the given {@link DatagramSocket}.
259 public static void untagDatagramSocket(DatagramSocket socket) throws SocketException {
260 SocketTagger.get().untag(socket);
264 * Start profiling data usage for current UID. Only one profiling session
265 * can be active at a time.
269 public static void startDataProfiling(Context context) {
270 synchronized (sProfilingLock) {
271 if (sActiveProfilingStart != null) {
272 throw new IllegalStateException("already profiling data");
275 // take snapshot in time; we calculate delta later
276 sActiveProfilingStart = getDataLayerSnapshotForUid(context);
281 * Stop profiling data usage for current UID.
283 * @return Detailed {@link NetworkStats} of data that occurred since last
284 * {@link #startDataProfiling(Context)} call.
287 public static NetworkStats stopDataProfiling(Context context) {
288 synchronized (sProfilingLock) {
289 if (sActiveProfilingStart == null) {
290 throw new IllegalStateException("not profiling data");
293 // subtract starting values and return delta
294 final NetworkStats profilingStop = getDataLayerSnapshotForUid(context);
295 final NetworkStats profilingDelta = NetworkStats.subtract(
296 profilingStop, sActiveProfilingStart, null, null);
297 sActiveProfilingStart = null;
298 return profilingDelta;
303 * Increment count of network operations performed under the accounting tag
304 * currently active on the calling thread. This can be used to derive
305 * bytes-per-operation.
307 * @param operationCount Number of operations to increment count by.
309 public static void incrementOperationCount(int operationCount) {
310 final int tag = getThreadStatsTag();
311 incrementOperationCount(tag, operationCount);
315 * Increment count of network operations performed under the given
316 * accounting tag. This can be used to derive bytes-per-operation.
318 * @param tag Accounting tag used in {@link #setThreadStatsTag(int)}.
319 * @param operationCount Number of operations to increment count by.
321 public static void incrementOperationCount(int tag, int operationCount) {
322 final int uid = android.os.Process.myUid();
324 getStatsService().incrementOperationCount(uid, tag, operationCount);
325 } catch (RemoteException e) {
326 throw e.rethrowFromSystemServer();
331 public static void closeQuietly(INetworkStatsSession session) {
332 // TODO: move to NetworkStatsService once it exists
333 if (session != null) {
336 } catch (RuntimeException rethrown) {
338 } catch (Exception ignored) {
344 * Return number of packets transmitted across mobile networks since device
345 * boot. Counts packets across all mobile network interfaces, and always
346 * increases monotonically since device boot. Statistics are measured at the
347 * network layer, so they include both TCP and UDP usage.
349 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
350 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
352 public static long getMobileTxPackets() {
354 for (String iface : getMobileIfaces()) {
355 total += getTxPackets(iface);
361 * Return number of packets received across mobile networks since device
362 * boot. Counts packets across all mobile network interfaces, and always
363 * increases monotonically since device boot. Statistics are measured at the
364 * network layer, so they include both TCP and UDP usage.
366 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
367 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
369 public static long getMobileRxPackets() {
371 for (String iface : getMobileIfaces()) {
372 total += getRxPackets(iface);
378 * Return number of bytes transmitted across mobile networks since device
379 * boot. Counts packets across all mobile network interfaces, and always
380 * increases monotonically since device boot. Statistics are measured at the
381 * network layer, so they include both TCP and UDP usage.
383 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
384 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
386 public static long getMobileTxBytes() {
388 for (String iface : getMobileIfaces()) {
389 total += getTxBytes(iface);
395 * Return number of bytes received across mobile networks since device boot.
396 * Counts packets across all mobile network interfaces, and always increases
397 * monotonically since device boot. Statistics are measured at the network
398 * layer, so they include both TCP and UDP usage.
400 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
401 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
403 public static long getMobileRxBytes() {
405 for (String iface : getMobileIfaces()) {
406 total += getRxBytes(iface);
412 public static long getMobileTcpRxPackets() {
414 for (String iface : getMobileIfaces()) {
415 final long stat = nativeGetIfaceStat(iface, TYPE_TCP_RX_PACKETS);
416 if (stat != UNSUPPORTED) {
424 public static long getMobileTcpTxPackets() {
426 for (String iface : getMobileIfaces()) {
427 final long stat = nativeGetIfaceStat(iface, TYPE_TCP_TX_PACKETS);
428 if (stat != UNSUPPORTED) {
436 public static long getTxPackets(String iface) {
437 return nativeGetIfaceStat(iface, TYPE_TX_PACKETS);
441 public static long getRxPackets(String iface) {
442 return nativeGetIfaceStat(iface, TYPE_RX_PACKETS);
446 public static long getTxBytes(String iface) {
447 return nativeGetIfaceStat(iface, TYPE_TX_BYTES);
451 public static long getRxBytes(String iface) {
452 return nativeGetIfaceStat(iface, TYPE_RX_BYTES);
456 * Return number of packets transmitted since device boot. Counts packets
457 * across all network interfaces, and always increases monotonically since
458 * device boot. Statistics are measured at the network layer, so they
459 * include both TCP and UDP usage.
461 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
462 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
464 public static long getTotalTxPackets() {
465 return nativeGetTotalStat(TYPE_TX_PACKETS);
469 * Return number of packets received since device boot. Counts packets
470 * across all network interfaces, and always increases monotonically since
471 * device boot. Statistics are measured at the network layer, so they
472 * include both TCP and UDP usage.
474 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
475 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
477 public static long getTotalRxPackets() {
478 return nativeGetTotalStat(TYPE_RX_PACKETS);
482 * Return number of bytes transmitted since device boot. Counts packets
483 * across all network interfaces, and always increases monotonically since
484 * device boot. Statistics are measured at the network layer, so they
485 * include both TCP and UDP usage.
487 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
488 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
490 public static long getTotalTxBytes() {
491 return nativeGetTotalStat(TYPE_TX_BYTES);
495 * Return number of bytes received since device boot. Counts packets across
496 * all network interfaces, and always increases monotonically since device
497 * boot. Statistics are measured at the network layer, so they include both
500 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
501 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
503 public static long getTotalRxBytes() {
504 return nativeGetTotalStat(TYPE_RX_BYTES);
508 * Return number of bytes transmitted by the given UID since device boot.
509 * Counts packets across all network interfaces, and always increases
510 * monotonically since device boot. Statistics are measured at the network
511 * layer, so they include both TCP and UDP usage.
513 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
514 * return {@link #UNSUPPORTED} on devices where statistics aren't available.
516 * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
517 * report traffic statistics for the calling UID. It will return
518 * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
519 * historical network statistics belonging to other UIDs, use
520 * {@link NetworkStatsManager}.
522 * @see android.os.Process#myUid()
523 * @see android.content.pm.ApplicationInfo#uid
525 public static long getUidTxBytes(int uid) {
526 // This isn't actually enforcing any security; it just returns the
527 // unsupported value. The real filtering is done at the kernel level.
528 final int callingUid = android.os.Process.myUid();
529 if (callingUid == android.os.Process.SYSTEM_UID || callingUid == uid) {
530 return nativeGetUidStat(uid, TYPE_TX_BYTES);
537 * Return number of bytes received by the given UID since device boot.
538 * Counts packets across all network interfaces, and always increases
539 * monotonically since device boot. Statistics are measured at the network
540 * layer, so they include both TCP and UDP usage.
542 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return
543 * {@link #UNSUPPORTED} on devices where statistics aren't available.
545 * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
546 * report traffic statistics for the calling UID. It will return
547 * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
548 * historical network statistics belonging to other UIDs, use
549 * {@link NetworkStatsManager}.
551 * @see android.os.Process#myUid()
552 * @see android.content.pm.ApplicationInfo#uid
554 public static long getUidRxBytes(int uid) {
555 // This isn't actually enforcing any security; it just returns the
556 // unsupported value. The real filtering is done at the kernel level.
557 final int callingUid = android.os.Process.myUid();
558 if (callingUid == android.os.Process.SYSTEM_UID || callingUid == uid) {
559 return nativeGetUidStat(uid, TYPE_RX_BYTES);
566 * Return number of packets transmitted by the given UID since device boot.
567 * Counts packets across all network interfaces, and always increases
568 * monotonically since device boot. Statistics are measured at the network
569 * layer, so they include both TCP and UDP usage.
571 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return
572 * {@link #UNSUPPORTED} on devices where statistics aren't available.
574 * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
575 * report traffic statistics for the calling UID. It will return
576 * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
577 * historical network statistics belonging to other UIDs, use
578 * {@link NetworkStatsManager}.
580 * @see android.os.Process#myUid()
581 * @see android.content.pm.ApplicationInfo#uid
583 public static long getUidTxPackets(int uid) {
584 // This isn't actually enforcing any security; it just returns the
585 // unsupported value. The real filtering is done at the kernel level.
586 final int callingUid = android.os.Process.myUid();
587 if (callingUid == android.os.Process.SYSTEM_UID || callingUid == uid) {
588 return nativeGetUidStat(uid, TYPE_TX_PACKETS);
595 * Return number of packets received by the given UID since device boot.
596 * Counts packets across all network interfaces, and always increases
597 * monotonically since device boot. Statistics are measured at the network
598 * layer, so they include both TCP and UDP usage.
600 * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return
601 * {@link #UNSUPPORTED} on devices where statistics aren't available.
603 * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
604 * report traffic statistics for the calling UID. It will return
605 * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
606 * historical network statistics belonging to other UIDs, use
607 * {@link NetworkStatsManager}.
609 * @see android.os.Process#myUid()
610 * @see android.content.pm.ApplicationInfo#uid
612 public static long getUidRxPackets(int uid) {
613 // This isn't actually enforcing any security; it just returns the
614 // unsupported value. The real filtering is done at the kernel level.
615 final int callingUid = android.os.Process.myUid();
616 if (callingUid == android.os.Process.SYSTEM_UID || callingUid == uid) {
617 return nativeGetUidStat(uid, TYPE_RX_PACKETS);
624 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
625 * transport layer statistics are no longer available, and will
626 * always return {@link #UNSUPPORTED}.
627 * @see #getUidTxBytes(int)
630 public static long getUidTcpTxBytes(int uid) {
635 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
636 * transport layer statistics are no longer available, and will
637 * always return {@link #UNSUPPORTED}.
638 * @see #getUidRxBytes(int)
641 public static long getUidTcpRxBytes(int uid) {
646 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
647 * transport layer statistics are no longer available, and will
648 * always return {@link #UNSUPPORTED}.
649 * @see #getUidTxBytes(int)
652 public static long getUidUdpTxBytes(int uid) {
657 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
658 * transport layer statistics are no longer available, and will
659 * always return {@link #UNSUPPORTED}.
660 * @see #getUidRxBytes(int)
663 public static long getUidUdpRxBytes(int uid) {
668 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
669 * transport layer statistics are no longer available, and will
670 * always return {@link #UNSUPPORTED}.
671 * @see #getUidTxPackets(int)
674 public static long getUidTcpTxSegments(int uid) {
679 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
680 * transport layer statistics are no longer available, and will
681 * always return {@link #UNSUPPORTED}.
682 * @see #getUidRxPackets(int)
685 public static long getUidTcpRxSegments(int uid) {
690 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
691 * transport layer statistics are no longer available, and will
692 * always return {@link #UNSUPPORTED}.
693 * @see #getUidTxPackets(int)
696 public static long getUidUdpTxPackets(int uid) {
701 * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
702 * transport layer statistics are no longer available, and will
703 * always return {@link #UNSUPPORTED}.
704 * @see #getUidRxPackets(int)
707 public static long getUidUdpRxPackets(int uid) {
712 * Return detailed {@link NetworkStats} for the current UID. Requires no
713 * special permission.
715 private static NetworkStats getDataLayerSnapshotForUid(Context context) {
716 // TODO: take snapshot locally, since proc file is now visible
717 final int uid = android.os.Process.myUid();
719 return getStatsService().getDataLayerSnapshotForUid(uid);
720 } catch (RemoteException e) {
721 throw e.rethrowFromSystemServer();
726 * Return set of any ifaces associated with mobile networks since boot.
727 * Interfaces are never removed from this list, so counters should always be
730 private static String[] getMobileIfaces() {
732 return getStatsService().getMobileIfaces();
733 } catch (RemoteException e) {
734 throw e.rethrowFromSystemServer();
738 // NOTE: keep these in sync with android_net_TrafficStats.cpp
739 private static final int TYPE_RX_BYTES = 0;
740 private static final int TYPE_RX_PACKETS = 1;
741 private static final int TYPE_TX_BYTES = 2;
742 private static final int TYPE_TX_PACKETS = 3;
743 private static final int TYPE_TCP_RX_PACKETS = 4;
744 private static final int TYPE_TCP_TX_PACKETS = 5;
746 private static native long nativeGetTotalStat(int type);
747 private static native long nativeGetIfaceStat(String iface, int type);
748 private static native long nativeGetUidStat(int uid, int type);