FileDocCategorySizeDatePackage
TrafficStats.javaAPI DocAndroid 5.1 API22654Thu Mar 12 22:22:10 GMT 2015android.net

TrafficStats

public class TrafficStats extends Object
Class that provides network traffic statistics. These statistics include bytes transmitted and received and network packets transmitted and received, over all interfaces, over the mobile interface, and on a per-UID basis.

These statistics may not be available on all platforms. If the statistics are not supported by this device, {@link #UNSUPPORTED} will be returned.

Fields Summary
public static final int
UNSUPPORTED
The return value to indicate that the device does not support the statistic.
public static final long
KB_IN_BYTES
public static final long
MB_IN_BYTES
public static final long
GB_IN_BYTES
public static final int
UID_REMOVED
Special UID value used when collecting {@link NetworkStatsHistory} for removed applications.
public static final int
UID_TETHERING
Special UID value used when collecting {@link NetworkStatsHistory} for tethering traffic.
public static final int
TAG_SYSTEM_DOWNLOAD
Default tag value for {@link DownloadManager} traffic.
public static final int
TAG_SYSTEM_MEDIA
Default tag value for {@link MediaPlayer} traffic.
public static final int
TAG_SYSTEM_BACKUP
Default tag value for {@link BackupManager} traffic.
private static INetworkStatsService
sStatsService
private static NetworkStats
sActiveProfilingStart
Snapshot of {@link NetworkStats} when the currently active profiling session started, or {@code null} if no session active.
private static Object
sProfilingLock
private static final int
TYPE_RX_BYTES
private static final int
TYPE_RX_PACKETS
private static final int
TYPE_TX_BYTES
private static final int
TYPE_TX_PACKETS
private static final int
TYPE_TCP_RX_PACKETS
private static final int
TYPE_TCP_TX_PACKETS
Constructors Summary
Methods Summary
public static voidclearThreadStatsTag()
Clear any active tag set to account {@link Socket} traffic originating from the current thread.

see
#setThreadStatsTag(int)

        NetworkManagementSocketTagger.setThreadSocketStatsTag(-1);
    
public static voidclearThreadStatsUid()
{@hide}

        NetworkManagementSocketTagger.setThreadSocketStatsUid(-1);
    
public static voidcloseQuietly(INetworkStatsSession session)
{@hide}

        // TODO: move to NetworkStatsService once it exists
        if (session != null) {
            try {
                session.close();
            } catch (RuntimeException rethrown) {
                throw rethrown;
            } catch (Exception ignored) {
            }
        }
    
private static NetworkStatsgetDataLayerSnapshotForUid(android.content.Context context)
Return detailed {@link NetworkStats} for the current UID. Requires no special permission.

        // TODO: take snapshot locally, since proc file is now visible
        final int uid = android.os.Process.myUid();
        try {
            return getStatsService().getDataLayerSnapshotForUid(uid);
        } catch (RemoteException e) {
            throw new RuntimeException(e);
        }
    
private static java.lang.String[]getMobileIfaces()
Return set of any ifaces associated with mobile networks since boot. Interfaces are never removed from this list, so counters should always be monotonic.

        try {
            return getStatsService().getMobileIfaces();
        } catch (RemoteException e) {
            throw new RuntimeException(e);
        }
    
public static longgetMobileRxBytes()
Return number of bytes received across mobile networks since device boot. Counts packets across all mobile network interfaces, and always increases monotonically since device boot. Statistics are measured at the network layer, so they include both TCP and UDP usage.

Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return {@link #UNSUPPORTED} on devices where statistics aren't available.

        long total = 0;
        for (String iface : getMobileIfaces()) {
            total += getRxBytes(iface);
        }
        return total;
    
public static longgetMobileRxPackets()
Return number of packets received across mobile networks since device boot. Counts packets across all mobile network interfaces, and always increases monotonically since device boot. Statistics are measured at the network layer, so they include both TCP and UDP usage.

Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return {@link #UNSUPPORTED} on devices where statistics aren't available.

        long total = 0;
        for (String iface : getMobileIfaces()) {
            total += getRxPackets(iface);
        }
        return total;
    
public static longgetMobileTcpRxPackets()
{@hide}

        long total = 0;
        for (String iface : getMobileIfaces()) {
            final long stat = nativeGetIfaceStat(iface, TYPE_TCP_RX_PACKETS);
            if (stat != UNSUPPORTED) {
                total += stat;
            }
        }
        return total;
    
public static longgetMobileTcpTxPackets()
{@hide}

        long total = 0;
        for (String iface : getMobileIfaces()) {
            final long stat = nativeGetIfaceStat(iface, TYPE_TCP_TX_PACKETS);
            if (stat != UNSUPPORTED) {
                total += stat;
            }
        }
        return total;
    
public static longgetMobileTxBytes()
Return number of bytes transmitted across mobile networks since device boot. Counts packets across all mobile network interfaces, and always increases monotonically since device boot. Statistics are measured at the network layer, so they include both TCP and UDP usage.

Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return {@link #UNSUPPORTED} on devices where statistics aren't available.

        long total = 0;
        for (String iface : getMobileIfaces()) {
            total += getTxBytes(iface);
        }
        return total;
    
public static longgetMobileTxPackets()
Return number of packets transmitted across mobile networks since device boot. Counts packets across all mobile network interfaces, and always increases monotonically since device boot. Statistics are measured at the network layer, so they include both TCP and UDP usage.

Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return {@link #UNSUPPORTED} on devices where statistics aren't available.

        long total = 0;
        for (String iface : getMobileIfaces()) {
            total += getTxPackets(iface);
        }
        return total;
    
public static longgetRxBytes(java.lang.String iface)
{@hide}

        return nativeGetIfaceStat(iface, TYPE_RX_BYTES);
    
public static longgetRxPackets(java.lang.String iface)
{@hide}

        return nativeGetIfaceStat(iface, TYPE_RX_PACKETS);
    
private static synchronized INetworkStatsServicegetStatsService()


         
        if (sStatsService == null) {
            sStatsService = INetworkStatsService.Stub.asInterface(
                    ServiceManager.getService(Context.NETWORK_STATS_SERVICE));
        }
        return sStatsService;
    
public static intgetThreadStatsTag()
Get the active tag used when accounting {@link Socket} traffic originating from the current thread. Only one active tag per thread is supported. {@link #tagSocket(Socket)}.

see
#setThreadStatsTag(int)

        return NetworkManagementSocketTagger.getThreadSocketStatsTag();
    
public static longgetTotalRxBytes()
Return number of bytes received since device boot. Counts packets across all network interfaces, and always increases monotonically since device boot. Statistics are measured at the network layer, so they include both TCP and UDP usage.

Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return {@link #UNSUPPORTED} on devices where statistics aren't available.

        return nativeGetTotalStat(TYPE_RX_BYTES);
    
public static longgetTotalRxPackets()
Return number of packets received since device boot. Counts packets across all network interfaces, and always increases monotonically since device boot. Statistics are measured at the network layer, so they include both TCP and UDP usage.

Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return {@link #UNSUPPORTED} on devices where statistics aren't available.

        return nativeGetTotalStat(TYPE_RX_PACKETS);
    
public static longgetTotalTxBytes()
Return number of bytes transmitted since device boot. Counts packets across all network interfaces, and always increases monotonically since device boot. Statistics are measured at the network layer, so they include both TCP and UDP usage.

Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return {@link #UNSUPPORTED} on devices where statistics aren't available.

        return nativeGetTotalStat(TYPE_TX_BYTES);
    
public static longgetTotalTxPackets()
Return number of packets transmitted since device boot. Counts packets across all network interfaces, and always increases monotonically since device boot. Statistics are measured at the network layer, so they include both TCP and UDP usage.

Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return {@link #UNSUPPORTED} on devices where statistics aren't available.

        return nativeGetTotalStat(TYPE_TX_PACKETS);
    
public static longgetTxBytes(java.lang.String iface)
{@hide}

        return nativeGetIfaceStat(iface, TYPE_TX_BYTES);
    
public static longgetTxPackets(java.lang.String iface)
{@hide}

        return nativeGetIfaceStat(iface, TYPE_TX_PACKETS);
    
public static longgetUidRxBytes(int uid)
Return number of bytes received by the given UID since device boot. Counts packets across all network interfaces, and always increases monotonically since device boot. Statistics are measured at the network layer, so they include both TCP and UDP usage.

Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return {@link #UNSUPPORTED} on devices where statistics aren't available.

see
android.os.Process#myUid()
see
android.content.pm.ApplicationInfo#uid

        return nativeGetUidStat(uid, TYPE_RX_BYTES);
    
public static longgetUidRxPackets(int uid)
Return number of packets received by the given UID since device boot. Counts packets across all network interfaces, and always increases monotonically since device boot. Statistics are measured at the network layer, so they include both TCP and UDP usage.

Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return {@link #UNSUPPORTED} on devices where statistics aren't available.

see
android.os.Process#myUid()
see
android.content.pm.ApplicationInfo#uid

        return nativeGetUidStat(uid, TYPE_RX_PACKETS);
    
public static longgetUidTcpRxBytes(int uid)

deprecated
Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, transport layer statistics are no longer available, and will always return {@link #UNSUPPORTED}.
see
#getUidRxBytes(int)

        return UNSUPPORTED;
    
public static longgetUidTcpRxSegments(int uid)

deprecated
Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, transport layer statistics are no longer available, and will always return {@link #UNSUPPORTED}.
see
#getUidRxPackets(int)

        return UNSUPPORTED;
    
public static longgetUidTcpTxBytes(int uid)

deprecated
Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, transport layer statistics are no longer available, and will always return {@link #UNSUPPORTED}.
see
#getUidTxBytes(int)

        return UNSUPPORTED;
    
public static longgetUidTcpTxSegments(int uid)

deprecated
Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, transport layer statistics are no longer available, and will always return {@link #UNSUPPORTED}.
see
#getUidTxPackets(int)

        return UNSUPPORTED;
    
public static longgetUidTxBytes(int uid)
Return number of bytes transmitted by the given UID since device boot. Counts packets across all network interfaces, and always increases monotonically since device boot. Statistics are measured at the network layer, so they include both TCP and UDP usage.

Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return {@link #UNSUPPORTED} on devices where statistics aren't available.

see
android.os.Process#myUid()
see
android.content.pm.ApplicationInfo#uid

        return nativeGetUidStat(uid, TYPE_TX_BYTES);
    
public static longgetUidTxPackets(int uid)
Return number of packets transmitted by the given UID since device boot. Counts packets across all network interfaces, and always increases monotonically since device boot. Statistics are measured at the network layer, so they include both TCP and UDP usage.

Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return {@link #UNSUPPORTED} on devices where statistics aren't available.

see
android.os.Process#myUid()
see
android.content.pm.ApplicationInfo#uid

        return nativeGetUidStat(uid, TYPE_TX_PACKETS);
    
public static longgetUidUdpRxBytes(int uid)

deprecated
Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, transport layer statistics are no longer available, and will always return {@link #UNSUPPORTED}.
see
#getUidRxBytes(int)

        return UNSUPPORTED;
    
public static longgetUidUdpRxPackets(int uid)

deprecated
Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, transport layer statistics are no longer available, and will always return {@link #UNSUPPORTED}.
see
#getUidRxPackets(int)

        return UNSUPPORTED;
    
public static longgetUidUdpTxBytes(int uid)

deprecated
Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, transport layer statistics are no longer available, and will always return {@link #UNSUPPORTED}.
see
#getUidTxBytes(int)

        return UNSUPPORTED;
    
public static longgetUidUdpTxPackets(int uid)

deprecated
Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, transport layer statistics are no longer available, and will always return {@link #UNSUPPORTED}.
see
#getUidTxPackets(int)

        return UNSUPPORTED;
    
public static voidincrementOperationCount(int operationCount)
Increment count of network operations performed under the accounting tag currently active on the calling thread. This can be used to derive bytes-per-operation.

param
operationCount Number of operations to increment count by.

        final int tag = getThreadStatsTag();
        incrementOperationCount(tag, operationCount);
    
public static voidincrementOperationCount(int tag, int operationCount)
Increment count of network operations performed under the given accounting tag. This can be used to derive bytes-per-operation.

param
tag Accounting tag used in {@link #setThreadStatsTag(int)}.
param
operationCount Number of operations to increment count by.

        final int uid = android.os.Process.myUid();
        try {
            getStatsService().incrementOperationCount(uid, tag, operationCount);
        } catch (RemoteException e) {
            throw new RuntimeException(e);
        }
    
private static native longnativeGetIfaceStat(java.lang.String iface, int type)

private static native longnativeGetTotalStat(int type)

private static native longnativeGetUidStat(int uid, int type)

public static voidsetThreadStatsTag(int tag)
Set active tag to use when accounting {@link Socket} traffic originating from the current thread. Only one active tag per thread is supported.

Changes only take effect during subsequent calls to {@link #tagSocket(Socket)}.

Tags between {@code 0xFFFFFF00} and {@code 0xFFFFFFFF} are reserved and used internally by system services like {@link DownloadManager} when performing traffic on behalf of an application.

see
#clearThreadStatsTag()


                                                                        
         
        NetworkManagementSocketTagger.setThreadSocketStatsTag(tag);
    
public static voidsetThreadStatsTagBackup()
System API for backup-related support components to tag network traffic appropriately.

hide

        setThreadStatsTag(TAG_SYSTEM_BACKUP);
    
public static voidsetThreadStatsUid(int uid)
Set specific UID to use when accounting {@link Socket} traffic originating from the current thread. Designed for use when performing an operation on behalf of another application.

Changes only take effect during subsequent calls to {@link #tagSocket(Socket)}.

To take effect, caller must hold {@link android.Manifest.permission#UPDATE_DEVICE_STATS} permission.

hide

        NetworkManagementSocketTagger.setThreadSocketStatsUid(uid);
    
public static voidstartDataProfiling(android.content.Context context)
Start profiling data usage for current UID. Only one profiling session can be active at a time.

hide

        synchronized (sProfilingLock) {
            if (sActiveProfilingStart != null) {
                throw new IllegalStateException("already profiling data");
            }

            // take snapshot in time; we calculate delta later
            sActiveProfilingStart = getDataLayerSnapshotForUid(context);
        }
    
public static NetworkStatsstopDataProfiling(android.content.Context context)
Stop profiling data usage for current UID.

return
Detailed {@link NetworkStats} of data that occurred since last {@link #startDataProfiling(Context)} call.
hide

        synchronized (sProfilingLock) {
            if (sActiveProfilingStart == null) {
                throw new IllegalStateException("not profiling data");
            }

            // subtract starting values and return delta
            final NetworkStats profilingStop = getDataLayerSnapshotForUid(context);
            final NetworkStats profilingDelta = NetworkStats.subtract(
                    profilingStop, sActiveProfilingStart, null, null);
            sActiveProfilingStart = null;
            return profilingDelta;
        }
    
public static voidtagSocket(java.net.Socket socket)
Tag the given {@link Socket} with any statistics parameters active for the current thread. Subsequent calls always replace any existing parameters. When finished, call {@link #untagSocket(Socket)} to remove statistics parameters.

see
#setThreadStatsTag(int)
see
#setThreadStatsUid(int)

        SocketTagger.get().tag(socket);
    
public static voiduntagSocket(java.net.Socket socket)
Remove any statistics parameters from the given {@link Socket}.

        SocketTagger.get().untag(socket);