• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 
17 package android.net;
18 
19 import android.annotation.RequiresPermission;
20 import android.annotation.SystemApi;
21 import android.app.DownloadManager;
22 import android.app.backup.BackupManager;
23 import android.app.usage.NetworkStatsManager;
24 import android.content.Context;
25 import android.media.MediaPlayer;
26 import android.os.RemoteException;
27 import android.os.ServiceManager;
28 
29 import com.android.server.NetworkManagementSocketTagger;
30 
31 import dalvik.system.SocketTagger;
32 
33 import java.net.DatagramSocket;
34 import java.net.Socket;
35 import java.net.SocketException;
36 
37 /**
38  * Class that provides network traffic statistics. These statistics include
39  * bytes transmitted and received and network packets transmitted and received,
40  * over all interfaces, over the mobile interface, and on a per-UID basis.
41  * <p>
42  * These statistics may not be available on all platforms. If the statistics are
43  * not supported by this device, {@link #UNSUPPORTED} will be returned.
44  * <p>
45  * Note that the statistics returned by this class reset and start from zero
46  * after every reboot. To access more robust historical network statistics data,
47  * use {@link NetworkStatsManager} instead.
48  */
49 public class TrafficStats {
50     /**
51      * The return value to indicate that the device does not support the statistic.
52      */
53     public final static int UNSUPPORTED = -1;
54 
55     /** @hide */
56     public static final long KB_IN_BYTES = 1024;
57     /** @hide */
58     public static final long MB_IN_BYTES = KB_IN_BYTES * 1024;
59     /** @hide */
60     public static final long GB_IN_BYTES = MB_IN_BYTES * 1024;
61     /** @hide */
62     public static final long TB_IN_BYTES = GB_IN_BYTES * 1024;
63     /** @hide */
64     public static final long PB_IN_BYTES = TB_IN_BYTES * 1024;
65 
66     /**
67      * Special UID value used when collecting {@link NetworkStatsHistory} for
68      * removed applications.
69      *
70      * @hide
71      */
72     public static final int UID_REMOVED = -4;
73 
74     /**
75      * Special UID value used when collecting {@link NetworkStatsHistory} for
76      * tethering traffic.
77      *
78      * @hide
79      */
80     public static final int UID_TETHERING = -5;
81 
82     /**
83      * Default tag value for {@link DownloadManager} traffic.
84      *
85      * @hide
86      */
87     public static final int TAG_SYSTEM_DOWNLOAD = 0xFFFFFF01;
88 
89     /**
90      * Default tag value for {@link MediaPlayer} traffic.
91      *
92      * @hide
93      */
94     public static final int TAG_SYSTEM_MEDIA = 0xFFFFFF02;
95 
96     /**
97      * Default tag value for {@link BackupManager} backup traffic; that is,
98      * traffic from the device to the storage backend.
99      *
100      * @hide
101      */
102     public static final int TAG_SYSTEM_BACKUP = 0xFFFFFF03;
103 
104     /**
105      * Default tag value for {@link BackupManager} restore traffic; that is,
106      * app data retrieved from the storage backend at install time.
107      *
108      * @hide
109      */
110     public static final int TAG_SYSTEM_RESTORE = 0xFFFFFF04;
111 
112     /**
113      * Default tag value for code (typically APKs) downloaded by an app store on
114      * behalf of the app, such as updates.
115      *
116      * @hide
117      */
118     public static final int TAG_SYSTEM_APP = 0xFFFFFF05;
119 
120     /** @hide */
121     public static final int TAG_SYSTEM_DHCP = 0xFFFFFF40;
122     /** @hide */
123     public static final int TAG_SYSTEM_NTP = 0xFFFFFF41;
124     /** @hide */
125     public static final int TAG_SYSTEM_PROBE = 0xFFFFFF42;
126     /** @hide */
127     public static final int TAG_SYSTEM_NEIGHBOR = 0xFFFFFF43;
128     /** @hide */
129     public static final int TAG_SYSTEM_GPS = 0xFFFFFF44;
130     /** @hide */
131     public static final int TAG_SYSTEM_PAC = 0xFFFFFF45;
132 
133     private static INetworkStatsService sStatsService;
134 
getStatsService()135     private synchronized static INetworkStatsService getStatsService() {
136         if (sStatsService == null) {
137             sStatsService = INetworkStatsService.Stub.asInterface(
138                     ServiceManager.getService(Context.NETWORK_STATS_SERVICE));
139         }
140         return sStatsService;
141     }
142 
143     /**
144      * Snapshot of {@link NetworkStats} when the currently active profiling
145      * session started, or {@code null} if no session active.
146      *
147      * @see #startDataProfiling(Context)
148      * @see #stopDataProfiling(Context)
149      */
150     private static NetworkStats sActiveProfilingStart;
151 
152     private static Object sProfilingLock = new Object();
153 
154     /**
155      * Set active tag to use when accounting {@link Socket} traffic originating
156      * from the current thread. Only one active tag per thread is supported.
157      * <p>
158      * Changes only take effect during subsequent calls to
159      * {@link #tagSocket(Socket)}.
160      * <p>
161      * Tags between {@code 0xFFFFFF00} and {@code 0xFFFFFFFF} are reserved and
162      * used internally by system services like {@link DownloadManager} when
163      * performing traffic on behalf of an application.
164      *
165      * @see #clearThreadStatsTag()
166      */
setThreadStatsTag(int tag)167     public static void setThreadStatsTag(int tag) {
168         NetworkManagementSocketTagger.setThreadSocketStatsTag(tag);
169     }
170 
171     /**
172      * Set active tag to use when accounting {@link Socket} traffic originating
173      * from the current thread. Only one active tag per thread is supported.
174      * <p>
175      * Changes only take effect during subsequent calls to
176      * {@link #tagSocket(Socket)}.
177      * <p>
178      * Tags between {@code 0xFFFFFF00} and {@code 0xFFFFFFFF} are reserved and
179      * used internally by system services like {@link DownloadManager} when
180      * performing traffic on behalf of an application.
181      *
182      * @return the current tag for the calling thread, which can be used to
183      *         restore any existing values after a nested operation is finished
184      */
getAndSetThreadStatsTag(int tag)185     public static int getAndSetThreadStatsTag(int tag) {
186         return NetworkManagementSocketTagger.setThreadSocketStatsTag(tag);
187     }
188 
189     /**
190      * Set active tag to use when accounting {@link Socket} traffic originating
191      * from the current thread. The tag used internally is well-defined to
192      * distinguish all backup-related traffic.
193      *
194      * @hide
195      */
196     @SystemApi
setThreadStatsTagBackup()197     public static void setThreadStatsTagBackup() {
198         setThreadStatsTag(TAG_SYSTEM_BACKUP);
199     }
200 
201     /**
202      * Set active tag to use when accounting {@link Socket} traffic originating
203      * from the current thread. The tag used internally is well-defined to
204      * distinguish all restore-related traffic.
205      *
206      * @hide
207      */
208     @SystemApi
setThreadStatsTagRestore()209     public static void setThreadStatsTagRestore() {
210         setThreadStatsTag(TAG_SYSTEM_RESTORE);
211     }
212 
213     /**
214      * Set active tag to use when accounting {@link Socket} traffic originating
215      * from the current thread. The tag used internally is well-defined to
216      * distinguish all code (typically APKs) downloaded by an app store on
217      * behalf of the app, such as updates.
218      *
219      * @hide
220      */
221     @SystemApi
setThreadStatsTagApp()222     public static void setThreadStatsTagApp() {
223         setThreadStatsTag(TAG_SYSTEM_APP);
224     }
225 
226     /**
227      * Get the active tag used when accounting {@link Socket} traffic originating
228      * from the current thread. Only one active tag per thread is supported.
229      * {@link #tagSocket(Socket)}.
230      *
231      * @see #setThreadStatsTag(int)
232      */
getThreadStatsTag()233     public static int getThreadStatsTag() {
234         return NetworkManagementSocketTagger.getThreadSocketStatsTag();
235     }
236 
237     /**
238      * Clear any active tag set to account {@link Socket} traffic originating
239      * from the current thread.
240      *
241      * @see #setThreadStatsTag(int)
242      */
clearThreadStatsTag()243     public static void clearThreadStatsTag() {
244         NetworkManagementSocketTagger.setThreadSocketStatsTag(-1);
245     }
246 
247     /**
248      * Set specific UID to use when accounting {@link Socket} traffic
249      * originating from the current thread. Designed for use when performing an
250      * operation on behalf of another application.
251      * <p>
252      * Changes only take effect during subsequent calls to
253      * {@link #tagSocket(Socket)}.
254      * <p>
255      * To take effect, caller must hold
256      * {@link android.Manifest.permission#UPDATE_DEVICE_STATS} permission.
257      *
258      * @hide
259      */
260     @SystemApi
261     @RequiresPermission(android.Manifest.permission.UPDATE_DEVICE_STATS)
setThreadStatsUid(int uid)262     public static void setThreadStatsUid(int uid) {
263         NetworkManagementSocketTagger.setThreadSocketStatsUid(uid);
264     }
265 
266     /**
267      * Clear any active UID set to account {@link Socket} traffic originating
268      * from the current thread.
269      *
270      * @see #setThreadStatsUid(int)
271      * @hide
272      */
273     @SystemApi
274     @RequiresPermission(android.Manifest.permission.UPDATE_DEVICE_STATS)
clearThreadStatsUid()275     public static void clearThreadStatsUid() {
276         NetworkManagementSocketTagger.setThreadSocketStatsUid(-1);
277     }
278 
279     /**
280      * Tag the given {@link Socket} with any statistics parameters active for
281      * the current thread. Subsequent calls always replace any existing
282      * parameters. When finished, call {@link #untagSocket(Socket)} to remove
283      * statistics parameters.
284      *
285      * @see #setThreadStatsTag(int)
286      */
tagSocket(Socket socket)287     public static void tagSocket(Socket socket) throws SocketException {
288         SocketTagger.get().tag(socket);
289     }
290 
291     /**
292      * Remove any statistics parameters from the given {@link Socket}.
293      */
untagSocket(Socket socket)294     public static void untagSocket(Socket socket) throws SocketException {
295         SocketTagger.get().untag(socket);
296     }
297 
298     /**
299      * Tag the given {@link DatagramSocket} with any statistics parameters
300      * active for the current thread. Subsequent calls always replace any
301      * existing parameters. When finished, call
302      * {@link #untagDatagramSocket(DatagramSocket)} to remove statistics
303      * parameters.
304      *
305      * @see #setThreadStatsTag(int)
306      */
tagDatagramSocket(DatagramSocket socket)307     public static void tagDatagramSocket(DatagramSocket socket) throws SocketException {
308         SocketTagger.get().tag(socket);
309     }
310 
311     /**
312      * Remove any statistics parameters from the given {@link DatagramSocket}.
313      */
untagDatagramSocket(DatagramSocket socket)314     public static void untagDatagramSocket(DatagramSocket socket) throws SocketException {
315         SocketTagger.get().untag(socket);
316     }
317 
318     /**
319      * Start profiling data usage for current UID. Only one profiling session
320      * can be active at a time.
321      *
322      * @hide
323      */
startDataProfiling(Context context)324     public static void startDataProfiling(Context context) {
325         synchronized (sProfilingLock) {
326             if (sActiveProfilingStart != null) {
327                 throw new IllegalStateException("already profiling data");
328             }
329 
330             // take snapshot in time; we calculate delta later
331             sActiveProfilingStart = getDataLayerSnapshotForUid(context);
332         }
333     }
334 
335     /**
336      * Stop profiling data usage for current UID.
337      *
338      * @return Detailed {@link NetworkStats} of data that occurred since last
339      *         {@link #startDataProfiling(Context)} call.
340      * @hide
341      */
stopDataProfiling(Context context)342     public static NetworkStats stopDataProfiling(Context context) {
343         synchronized (sProfilingLock) {
344             if (sActiveProfilingStart == null) {
345                 throw new IllegalStateException("not profiling data");
346             }
347 
348             // subtract starting values and return delta
349             final NetworkStats profilingStop = getDataLayerSnapshotForUid(context);
350             final NetworkStats profilingDelta = NetworkStats.subtract(
351                     profilingStop, sActiveProfilingStart, null, null);
352             sActiveProfilingStart = null;
353             return profilingDelta;
354         }
355     }
356 
357     /**
358      * Increment count of network operations performed under the accounting tag
359      * currently active on the calling thread. This can be used to derive
360      * bytes-per-operation.
361      *
362      * @param operationCount Number of operations to increment count by.
363      */
incrementOperationCount(int operationCount)364     public static void incrementOperationCount(int operationCount) {
365         final int tag = getThreadStatsTag();
366         incrementOperationCount(tag, operationCount);
367     }
368 
369     /**
370      * Increment count of network operations performed under the given
371      * accounting tag. This can be used to derive bytes-per-operation.
372      *
373      * @param tag Accounting tag used in {@link #setThreadStatsTag(int)}.
374      * @param operationCount Number of operations to increment count by.
375      */
incrementOperationCount(int tag, int operationCount)376     public static void incrementOperationCount(int tag, int operationCount) {
377         final int uid = android.os.Process.myUid();
378         try {
379             getStatsService().incrementOperationCount(uid, tag, operationCount);
380         } catch (RemoteException e) {
381             throw e.rethrowFromSystemServer();
382         }
383     }
384 
385     /** {@hide} */
closeQuietly(INetworkStatsSession session)386     public static void closeQuietly(INetworkStatsSession session) {
387         // TODO: move to NetworkStatsService once it exists
388         if (session != null) {
389             try {
390                 session.close();
391             } catch (RuntimeException rethrown) {
392                 throw rethrown;
393             } catch (Exception ignored) {
394             }
395         }
396     }
397 
398     /**
399      * Return number of packets transmitted across mobile networks since device
400      * boot. Counts packets across all mobile network interfaces, and always
401      * increases monotonically since device boot. Statistics are measured at the
402      * network layer, so they include both TCP and UDP usage.
403      * <p>
404      * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
405      * return {@link #UNSUPPORTED} on devices where statistics aren't available.
406      */
getMobileTxPackets()407     public static long getMobileTxPackets() {
408         long total = 0;
409         for (String iface : getMobileIfaces()) {
410             total += getTxPackets(iface);
411         }
412         return total;
413     }
414 
415     /**
416      * Return number of packets received across mobile networks since device
417      * boot. Counts packets across all mobile network interfaces, and always
418      * increases monotonically since device boot. Statistics are measured at the
419      * network layer, so they include both TCP and UDP usage.
420      * <p>
421      * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
422      * return {@link #UNSUPPORTED} on devices where statistics aren't available.
423      */
getMobileRxPackets()424     public static long getMobileRxPackets() {
425         long total = 0;
426         for (String iface : getMobileIfaces()) {
427             total += getRxPackets(iface);
428         }
429         return total;
430     }
431 
432     /**
433      * Return number of bytes transmitted across mobile networks since device
434      * boot. Counts packets across all mobile network interfaces, and always
435      * increases monotonically since device boot. Statistics are measured at the
436      * network layer, so they include both TCP and UDP usage.
437      * <p>
438      * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
439      * return {@link #UNSUPPORTED} on devices where statistics aren't available.
440      */
getMobileTxBytes()441     public static long getMobileTxBytes() {
442         long total = 0;
443         for (String iface : getMobileIfaces()) {
444             total += getTxBytes(iface);
445         }
446         return total;
447     }
448 
449     /**
450      * Return number of bytes received across mobile networks since device boot.
451      * Counts packets across all mobile network interfaces, and always increases
452      * monotonically since device boot. Statistics are measured at the network
453      * layer, so they include both TCP and UDP usage.
454      * <p>
455      * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
456      * return {@link #UNSUPPORTED} on devices where statistics aren't available.
457      */
getMobileRxBytes()458     public static long getMobileRxBytes() {
459         long total = 0;
460         for (String iface : getMobileIfaces()) {
461             total += getRxBytes(iface);
462         }
463         return total;
464     }
465 
466     /** {@hide} */
getMobileTcpRxPackets()467     public static long getMobileTcpRxPackets() {
468         long total = 0;
469         for (String iface : getMobileIfaces()) {
470             final long stat = nativeGetIfaceStat(iface, TYPE_TCP_RX_PACKETS);
471             if (stat != UNSUPPORTED) {
472                 total += stat;
473             }
474         }
475         return total;
476     }
477 
478     /** {@hide} */
getMobileTcpTxPackets()479     public static long getMobileTcpTxPackets() {
480         long total = 0;
481         for (String iface : getMobileIfaces()) {
482             final long stat = nativeGetIfaceStat(iface, TYPE_TCP_TX_PACKETS);
483             if (stat != UNSUPPORTED) {
484                 total += stat;
485             }
486         }
487         return total;
488     }
489 
490     /** {@hide} */
getTxPackets(String iface)491     public static long getTxPackets(String iface) {
492         return nativeGetIfaceStat(iface, TYPE_TX_PACKETS);
493     }
494 
495     /** {@hide} */
getRxPackets(String iface)496     public static long getRxPackets(String iface) {
497         return nativeGetIfaceStat(iface, TYPE_RX_PACKETS);
498     }
499 
500     /** {@hide} */
getTxBytes(String iface)501     public static long getTxBytes(String iface) {
502         return nativeGetIfaceStat(iface, TYPE_TX_BYTES);
503     }
504 
505     /** {@hide} */
getRxBytes(String iface)506     public static long getRxBytes(String iface) {
507         return nativeGetIfaceStat(iface, TYPE_RX_BYTES);
508     }
509 
510     /**
511      * Return number of packets transmitted since device boot. Counts packets
512      * across all network interfaces, and always increases monotonically since
513      * device boot. Statistics are measured at the network layer, so they
514      * include both TCP and UDP usage.
515      * <p>
516      * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
517      * return {@link #UNSUPPORTED} on devices where statistics aren't available.
518      */
getTotalTxPackets()519     public static long getTotalTxPackets() {
520         return nativeGetTotalStat(TYPE_TX_PACKETS);
521     }
522 
523     /**
524      * Return number of packets received since device boot. Counts packets
525      * across all network interfaces, and always increases monotonically since
526      * device boot. Statistics are measured at the network layer, so they
527      * include both TCP and UDP usage.
528      * <p>
529      * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
530      * return {@link #UNSUPPORTED} on devices where statistics aren't available.
531      */
getTotalRxPackets()532     public static long getTotalRxPackets() {
533         return nativeGetTotalStat(TYPE_RX_PACKETS);
534     }
535 
536     /**
537      * Return number of bytes transmitted since device boot. Counts packets
538      * across all network interfaces, and always increases monotonically since
539      * device boot. Statistics are measured at the network layer, so they
540      * include both TCP and UDP usage.
541      * <p>
542      * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
543      * return {@link #UNSUPPORTED} on devices where statistics aren't available.
544      */
getTotalTxBytes()545     public static long getTotalTxBytes() {
546         return nativeGetTotalStat(TYPE_TX_BYTES);
547     }
548 
549     /**
550      * Return number of bytes received since device boot. Counts packets across
551      * all network interfaces, and always increases monotonically since device
552      * boot. Statistics are measured at the network layer, so they include both
553      * TCP and UDP usage.
554      * <p>
555      * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
556      * return {@link #UNSUPPORTED} on devices where statistics aren't available.
557      */
getTotalRxBytes()558     public static long getTotalRxBytes() {
559         return nativeGetTotalStat(TYPE_RX_BYTES);
560     }
561 
562     /**
563      * Return number of bytes transmitted by the given UID since device boot.
564      * Counts packets across all network interfaces, and always increases
565      * monotonically since device boot. Statistics are measured at the network
566      * layer, so they include both TCP and UDP usage.
567      * <p>
568      * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may
569      * return {@link #UNSUPPORTED} on devices where statistics aren't available.
570      * <p>
571      * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
572      * report traffic statistics for the calling UID. It will return
573      * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
574      * historical network statistics belonging to other UIDs, use
575      * {@link NetworkStatsManager}.
576      *
577      * @see android.os.Process#myUid()
578      * @see android.content.pm.ApplicationInfo#uid
579      */
getUidTxBytes(int uid)580     public static long getUidTxBytes(int uid) {
581         // This isn't actually enforcing any security; it just returns the
582         // unsupported value. The real filtering is done at the kernel level.
583         final int callingUid = android.os.Process.myUid();
584         if (callingUid == android.os.Process.SYSTEM_UID || callingUid == uid) {
585             return nativeGetUidStat(uid, TYPE_TX_BYTES);
586         } else {
587             return UNSUPPORTED;
588         }
589     }
590 
591     /**
592      * Return number of bytes received by the given UID since device boot.
593      * Counts packets across all network interfaces, and always increases
594      * monotonically since device boot. Statistics are measured at the network
595      * layer, so they include both TCP and UDP usage.
596      * <p>
597      * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return
598      * {@link #UNSUPPORTED} on devices where statistics aren't available.
599      * <p>
600      * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
601      * report traffic statistics for the calling UID. It will return
602      * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
603      * historical network statistics belonging to other UIDs, use
604      * {@link NetworkStatsManager}.
605      *
606      * @see android.os.Process#myUid()
607      * @see android.content.pm.ApplicationInfo#uid
608      */
getUidRxBytes(int uid)609     public static long getUidRxBytes(int uid) {
610         // This isn't actually enforcing any security; it just returns the
611         // unsupported value. The real filtering is done at the kernel level.
612         final int callingUid = android.os.Process.myUid();
613         if (callingUid == android.os.Process.SYSTEM_UID || callingUid == uid) {
614             return nativeGetUidStat(uid, TYPE_RX_BYTES);
615         } else {
616             return UNSUPPORTED;
617         }
618     }
619 
620     /**
621      * Return number of packets transmitted by the given UID since device boot.
622      * Counts packets across all network interfaces, and always increases
623      * monotonically since device boot. Statistics are measured at the network
624      * layer, so they include both TCP and UDP usage.
625      * <p>
626      * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return
627      * {@link #UNSUPPORTED} on devices where statistics aren't available.
628      * <p>
629      * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
630      * report traffic statistics for the calling UID. It will return
631      * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
632      * historical network statistics belonging to other UIDs, use
633      * {@link NetworkStatsManager}.
634      *
635      * @see android.os.Process#myUid()
636      * @see android.content.pm.ApplicationInfo#uid
637      */
getUidTxPackets(int uid)638     public static long getUidTxPackets(int uid) {
639         // This isn't actually enforcing any security; it just returns the
640         // unsupported value. The real filtering is done at the kernel level.
641         final int callingUid = android.os.Process.myUid();
642         if (callingUid == android.os.Process.SYSTEM_UID || callingUid == uid) {
643             return nativeGetUidStat(uid, TYPE_TX_PACKETS);
644         } else {
645             return UNSUPPORTED;
646         }
647     }
648 
649     /**
650      * Return number of packets received by the given UID since device boot.
651      * Counts packets across all network interfaces, and always increases
652      * monotonically since device boot. Statistics are measured at the network
653      * layer, so they include both TCP and UDP usage.
654      * <p>
655      * Before {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2}, this may return
656      * {@link #UNSUPPORTED} on devices where statistics aren't available.
657      * <p>
658      * Starting in {@link android.os.Build.VERSION_CODES#N} this will only
659      * report traffic statistics for the calling UID. It will return
660      * {@link #UNSUPPORTED} for all other UIDs for privacy reasons. To access
661      * historical network statistics belonging to other UIDs, use
662      * {@link NetworkStatsManager}.
663      *
664      * @see android.os.Process#myUid()
665      * @see android.content.pm.ApplicationInfo#uid
666      */
getUidRxPackets(int uid)667     public static long getUidRxPackets(int uid) {
668         // This isn't actually enforcing any security; it just returns the
669         // unsupported value. The real filtering is done at the kernel level.
670         final int callingUid = android.os.Process.myUid();
671         if (callingUid == android.os.Process.SYSTEM_UID || callingUid == uid) {
672             return nativeGetUidStat(uid, TYPE_RX_PACKETS);
673         } else {
674             return UNSUPPORTED;
675         }
676     }
677 
678     /**
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 #getUidTxBytes(int)
683      */
684     @Deprecated
getUidTcpTxBytes(int uid)685     public static long getUidTcpTxBytes(int uid) {
686         return UNSUPPORTED;
687     }
688 
689     /**
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 #getUidRxBytes(int)
694      */
695     @Deprecated
getUidTcpRxBytes(int uid)696     public static long getUidTcpRxBytes(int uid) {
697         return UNSUPPORTED;
698     }
699 
700     /**
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 #getUidTxBytes(int)
705      */
706     @Deprecated
getUidUdpTxBytes(int uid)707     public static long getUidUdpTxBytes(int uid) {
708         return UNSUPPORTED;
709     }
710 
711     /**
712      * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
713      *             transport layer statistics are no longer available, and will
714      *             always return {@link #UNSUPPORTED}.
715      * @see #getUidRxBytes(int)
716      */
717     @Deprecated
getUidUdpRxBytes(int uid)718     public static long getUidUdpRxBytes(int uid) {
719         return UNSUPPORTED;
720     }
721 
722     /**
723      * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
724      *             transport layer statistics are no longer available, and will
725      *             always return {@link #UNSUPPORTED}.
726      * @see #getUidTxPackets(int)
727      */
728     @Deprecated
getUidTcpTxSegments(int uid)729     public static long getUidTcpTxSegments(int uid) {
730         return UNSUPPORTED;
731     }
732 
733     /**
734      * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
735      *             transport layer statistics are no longer available, and will
736      *             always return {@link #UNSUPPORTED}.
737      * @see #getUidRxPackets(int)
738      */
739     @Deprecated
getUidTcpRxSegments(int uid)740     public static long getUidTcpRxSegments(int uid) {
741         return UNSUPPORTED;
742     }
743 
744     /**
745      * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
746      *             transport layer statistics are no longer available, and will
747      *             always return {@link #UNSUPPORTED}.
748      * @see #getUidTxPackets(int)
749      */
750     @Deprecated
getUidUdpTxPackets(int uid)751     public static long getUidUdpTxPackets(int uid) {
752         return UNSUPPORTED;
753     }
754 
755     /**
756      * @deprecated Starting in {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
757      *             transport layer statistics are no longer available, and will
758      *             always return {@link #UNSUPPORTED}.
759      * @see #getUidRxPackets(int)
760      */
761     @Deprecated
getUidUdpRxPackets(int uid)762     public static long getUidUdpRxPackets(int uid) {
763         return UNSUPPORTED;
764     }
765 
766     /**
767      * Return detailed {@link NetworkStats} for the current UID. Requires no
768      * special permission.
769      */
getDataLayerSnapshotForUid(Context context)770     private static NetworkStats getDataLayerSnapshotForUid(Context context) {
771         // TODO: take snapshot locally, since proc file is now visible
772         final int uid = android.os.Process.myUid();
773         try {
774             return getStatsService().getDataLayerSnapshotForUid(uid);
775         } catch (RemoteException e) {
776             throw e.rethrowFromSystemServer();
777         }
778     }
779 
780     /**
781      * Return set of any ifaces associated with mobile networks since boot.
782      * Interfaces are never removed from this list, so counters should always be
783      * monotonic.
784      */
getMobileIfaces()785     private static String[] getMobileIfaces() {
786         try {
787             return getStatsService().getMobileIfaces();
788         } catch (RemoteException e) {
789             throw e.rethrowFromSystemServer();
790         }
791     }
792 
793     // NOTE: keep these in sync with android_net_TrafficStats.cpp
794     private static final int TYPE_RX_BYTES = 0;
795     private static final int TYPE_RX_PACKETS = 1;
796     private static final int TYPE_TX_BYTES = 2;
797     private static final int TYPE_TX_PACKETS = 3;
798     private static final int TYPE_TCP_RX_PACKETS = 4;
799     private static final int TYPE_TCP_TX_PACKETS = 5;
800 
nativeGetTotalStat(int type)801     private static native long nativeGetTotalStat(int type);
nativeGetIfaceStat(String iface, int type)802     private static native long nativeGetIfaceStat(String iface, int type);
nativeGetUidStat(int uid, int type)803     private static native long nativeGetUidStat(int uid, int type);
804 }
805