TrafficStats.java revision eaef351afcd586d5a84e80455f12f72fd12213ef
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
17package android.net;
18
19import android.app.DownloadManager;
20import android.app.backup.BackupManager;
21import android.content.Context;
22import android.media.MediaPlayer;
23import android.os.IBinder;
24import android.os.INetworkManagementService;
25import android.os.RemoteException;
26import android.os.ServiceManager;
27
28import com.android.server.NetworkManagementSocketTagger;
29
30import dalvik.system.SocketTagger;
31import java.net.Socket;
32import java.net.SocketException;
33
34/**
35 * Class that provides network traffic statistics.  These statistics include
36 * bytes transmitted and received and network packets transmitted and received,
37 * over all interfaces, over the mobile interface, and on a per-UID basis.
38 * <p>
39 * These statistics may not be available on all platforms.  If the statistics
40 * are not supported by this device, {@link #UNSUPPORTED} will be returned.
41 */
42public class TrafficStats {
43    /**
44     * The return value to indicate that the device does not support the statistic.
45     */
46    public final static int UNSUPPORTED = -1;
47
48    /**
49     * Special UID value used when collecting {@link NetworkStatsHistory} for
50     * removed applications.
51     *
52     * @hide
53     */
54    public static final int UID_REMOVED = -4;
55
56    /**
57     * Default tag value for {@link DownloadManager} traffic.
58     *
59     * @hide
60     */
61    public static final int TAG_SYSTEM_DOWNLOAD = 0xFFFF0001;
62
63    /**
64     * Default tag value for {@link MediaPlayer} traffic.
65     *
66     * @hide
67     */
68    public static final int TAG_SYSTEM_MEDIA = 0xFFFF0002;
69
70    /**
71     * Default tag value for {@link BackupManager} traffic.
72     *
73     * @hide
74     */
75    public static final int TAG_SYSTEM_BACKUP = 0xFFFF0003;
76
77    /**
78     * Snapshot of {@link NetworkStats} when the currently active profiling
79     * session started, or {@code null} if no session active.
80     *
81     * @see #startDataProfiling(Context)
82     * @see #stopDataProfiling(Context)
83     */
84    private static NetworkStats sActiveProfilingStart;
85
86    private static Object sProfilingLock = new Object();
87
88    /**
89     * Set active tag to use when accounting {@link Socket} traffic originating
90     * from the current thread. Only one active tag per thread is supported.
91     * <p>
92     * Changes only take effect during subsequent calls to
93     * {@link #tagSocket(Socket)}.
94     */
95    public static void setThreadStatsTag(int tag) {
96        NetworkManagementSocketTagger.setThreadSocketStatsTag(tag);
97    }
98
99    /**
100     * Get the active tag used when accounting {@link Socket} traffic originating
101     * from the current thread. Only one active tag per thread is supported.
102     * {@link #tagSocket(Socket)}.
103     */
104    public static int getThreadStatsTag() {
105        return NetworkManagementSocketTagger.getThreadSocketStatsTag();
106    }
107
108    /**
109     * @deprecated unsupported, will eventually be removed
110     */
111    @Deprecated
112    public static void setThreadStatsTag(String tag) {
113        setThreadStatsTag(tag.hashCode());
114    }
115
116    public static void clearThreadStatsTag() {
117        NetworkManagementSocketTagger.setThreadSocketStatsTag(-1);
118    }
119
120    /**
121     * Set specific UID to use when accounting {@link Socket} traffic
122     * originating from the current thread. Designed for use when performing an
123     * operation on behalf of another application.
124     * <p>
125     * Changes only take effect during subsequent calls to
126     * {@link #tagSocket(Socket)}.
127     * <p>
128     * To take effect, caller must hold
129     * {@link android.Manifest.permission#UPDATE_DEVICE_STATS} permission.
130     *
131     * {@hide}
132     */
133    public static void setThreadStatsUid(int uid) {
134        NetworkManagementSocketTagger.setThreadSocketStatsUid(uid);
135    }
136
137    /** {@hide} */
138    public static void clearThreadStatsUid() {
139        NetworkManagementSocketTagger.setThreadSocketStatsUid(-1);
140    }
141
142    /**
143     * Tag the given {@link Socket} with any statistics parameters active for
144     * the current thread. Subsequent calls always replace any existing
145     * parameters. When finished, call {@link #untagSocket(Socket)} to remove
146     * statistics parameters.
147     *
148     * @see #setThreadStatsTag(int)
149     * @see #setThreadStatsUid(int)
150     */
151    public static void tagSocket(Socket socket) throws SocketException {
152        SocketTagger.get().tag(socket);
153    }
154
155    /**
156     * Remove any statistics parameters from the given {@link Socket}.
157     */
158    public static void untagSocket(Socket socket) throws SocketException {
159        SocketTagger.get().untag(socket);
160    }
161
162    /**
163     * Start profiling data usage for current UID. Only one profiling session
164     * can be active at a time.
165     *
166     * @hide
167     */
168    public static void startDataProfiling(Context context) {
169        synchronized (sProfilingLock) {
170            if (sActiveProfilingStart != null) {
171                throw new IllegalStateException("already profiling data");
172            }
173
174            // take snapshot in time; we calculate delta later
175            sActiveProfilingStart = getNetworkStatsForUid(context);
176        }
177    }
178
179    /**
180     * Stop profiling data usage for current UID.
181     *
182     * @return Detailed {@link NetworkStats} of data that occurred since last
183     *         {@link #startDataProfiling(Context)} call.
184     * @hide
185     */
186    public static NetworkStats stopDataProfiling(Context context) {
187        synchronized (sProfilingLock) {
188            if (sActiveProfilingStart == null) {
189                throw new IllegalStateException("not profiling data");
190            }
191
192            // subtract starting values and return delta
193            final NetworkStats profilingStop = getNetworkStatsForUid(context);
194            final NetworkStats profilingDelta = profilingStop.subtractClamped(
195                    sActiveProfilingStart);
196            sActiveProfilingStart = null;
197            return profilingDelta;
198        }
199    }
200
201    /**
202     * Get the total number of packets transmitted through the mobile interface.
203     *
204     * @return number of packets.  If the statistics are not supported by this device,
205     * {@link #UNSUPPORTED} will be returned.
206     */
207    public static native long getMobileTxPackets();
208
209    /**
210     * Get the total number of packets received through the mobile interface.
211     *
212     * @return number of packets.  If the statistics are not supported by this device,
213     * {@link #UNSUPPORTED} will be returned.
214     */
215    public static native long getMobileRxPackets();
216
217    /**
218     * Get the total number of bytes transmitted through the mobile interface.
219     *
220     * @return number of bytes.  If the statistics are not supported by this device,
221     * {@link #UNSUPPORTED} will be returned.
222     */
223      public static native long getMobileTxBytes();
224
225    /**
226     * Get the total number of bytes received through the mobile interface.
227     *
228     * @return number of bytes.  If the statistics are not supported by this device,
229     * {@link #UNSUPPORTED} will be returned.
230     */
231    public static native long getMobileRxBytes();
232
233    /**
234     * Get the total number of packets transmitted through the specified interface.
235     *
236     * @return number of packets.  If the statistics are not supported by this interface,
237     * {@link #UNSUPPORTED} will be returned.
238     * @hide
239     */
240    public static native long getTxPackets(String iface);
241
242    /**
243     * Get the total number of packets received through the specified interface.
244     *
245     * @return number of packets.  If the statistics are not supported by this interface,
246     * {@link #UNSUPPORTED} will be returned.
247     * @hide
248     */
249    public static native long getRxPackets(String iface);
250
251    /**
252     * Get the total number of bytes transmitted through the specified interface.
253     *
254     * @return number of bytes.  If the statistics are not supported by this interface,
255     * {@link #UNSUPPORTED} will be returned.
256     * @hide
257     */
258    public static native long getTxBytes(String iface);
259
260    /**
261     * Get the total number of bytes received through the specified interface.
262     *
263     * @return number of bytes.  If the statistics are not supported by this interface,
264     * {@link #UNSUPPORTED} will be returned.
265     * @hide
266     */
267    public static native long getRxBytes(String iface);
268
269
270    /**
271     * Get the total number of packets sent through all network interfaces.
272     *
273     * @return the number of packets.  If the statistics are not supported by this device,
274     * {@link #UNSUPPORTED} will be returned.
275     */
276    public static native long getTotalTxPackets();
277
278    /**
279     * Get the total number of packets received through all network interfaces.
280     *
281     * @return number of packets.  If the statistics are not supported by this device,
282     * {@link #UNSUPPORTED} will be returned.
283     */
284    public static native long getTotalRxPackets();
285
286    /**
287     * Get the total number of bytes sent through all network interfaces.
288     *
289     * @return number of bytes.  If the statistics are not supported by this device,
290     * {@link #UNSUPPORTED} will be returned.
291     */
292    public static native long getTotalTxBytes();
293
294    /**
295     * Get the total number of bytes received through all network interfaces.
296     *
297     * @return number of bytes.  If the statistics are not supported by this device,
298     * {@link #UNSUPPORTED} will be returned.
299     */
300    public static native long getTotalRxBytes();
301
302    /**
303     * Get the number of bytes sent through the network for this UID.
304     * The statistics are across all interfaces.
305     *
306     * {@see android.os.Process#myUid()}.
307     *
308     * @param uid The UID of the process to examine.
309     * @return number of bytes.  If the statistics are not supported by this device,
310     * {@link #UNSUPPORTED} will be returned.
311     */
312    public static native long getUidTxBytes(int uid);
313
314    /**
315     * Get the number of bytes received through the network for this UID.
316     * The statistics are across all interfaces.
317     *
318     * {@see android.os.Process#myUid()}.
319     *
320     * @param uid The UID of the process to examine.
321     * @return number of bytes
322     */
323    public static native long getUidRxBytes(int uid);
324
325    /**
326     * Get the number of packets (TCP segments + UDP) sent through
327     * the network for this UID.
328     * The statistics are across all interfaces.
329     *
330     * {@see android.os.Process#myUid()}.
331     *
332     * @param uid The UID of the process to examine.
333     * @return number of packets.
334     * If the statistics are not supported by this device,
335     * {@link #UNSUPPORTED} will be returned.
336     */
337    public static native long getUidTxPackets(int uid);
338
339    /**
340     * Get the number of packets (TCP segments + UDP) received through
341     * the network for this UID.
342     * The statistics are across all interfaces.
343     *
344     * {@see android.os.Process#myUid()}.
345     *
346     * @param uid The UID of the process to examine.
347     * @return number of packets
348     */
349    public static native long getUidRxPackets(int uid);
350
351    /**
352     * Get the number of TCP payload bytes sent for this UID.
353     * This total does not include protocol and control overheads at
354     * the transport and the lower layers of the networking stack.
355     * The statistics are across all interfaces.
356     *
357     * {@see android.os.Process#myUid()}.
358     *
359     * @param uid The UID of the process to examine.
360     * @return number of bytes.  If the statistics are not supported by this device,
361     * {@link #UNSUPPORTED} will be returned.
362     */
363    public static native long getUidTcpTxBytes(int uid);
364
365    /**
366     * Get the number of TCP payload bytes received for this UID.
367     * This total does not include protocol and control overheads at
368     * the transport and the lower layers of the networking stack.
369     * The statistics are across all interfaces.
370     *
371     * {@see android.os.Process#myUid()}.
372     *
373     * @param uid The UID of the process to examine.
374     * @return number of bytes.  If the statistics are not supported by this device,
375     * {@link #UNSUPPORTED} will be returned.
376     */
377    public static native long getUidTcpRxBytes(int uid);
378
379    /**
380     * Get the number of UDP payload bytes sent for this UID.
381     * This total does not include protocol and control overheads at
382     * the transport and the lower layers of the networking stack.
383     * The statistics are across all interfaces.
384     *
385     * {@see android.os.Process#myUid()}.
386     *
387     * @param uid The UID of the process to examine.
388     * @return number of bytes.  If the statistics are not supported by this device,
389     * {@link #UNSUPPORTED} will be returned.
390     */
391    public static native long getUidUdpTxBytes(int uid);
392
393    /**
394     * Get the number of UDP payload bytes received for this UID.
395     * This total does not include protocol and control overheads at
396     * the transport and the lower layers of the networking stack.
397     * The statistics are across all interfaces.
398     *
399     * {@see android.os.Process#myUid()}.
400     *
401     * @param uid The UID of the process to examine.
402     * @return number of bytes.  If the statistics are not supported by this device,
403     * {@link #UNSUPPORTED} will be returned.
404     */
405    public static native long getUidUdpRxBytes(int uid);
406
407    /**
408     * Get the number of TCP segments sent for this UID.
409     * Does not include TCP control packets (SYN/ACKs/FIN/..).
410     * The statistics are across all interfaces.
411     *
412     * {@see android.os.Process#myUid()}.
413     *
414     * @param uid The UID of the process to examine.
415     * @return number of TCP segments.  If the statistics are not supported by this device,
416     * {@link #UNSUPPORTED} will be returned.
417     */
418    public static native long getUidTcpTxSegments(int uid);
419
420    /**
421     * Get the number of TCP segments received for this UID.
422     * Does not include TCP control packets (SYN/ACKs/FIN/..).
423     * The statistics are across all interfaces.
424     *
425     * {@see android.os.Process#myUid()}.
426     *
427     * @param uid The UID of the process to examine.
428     * @return number of TCP segments.  If the statistics are not supported by this device,
429     * {@link #UNSUPPORTED} will be returned.
430     */
431    public static native long getUidTcpRxSegments(int uid);
432
433
434    /**
435     * Get the number of UDP packets sent for this UID.
436     * Includes DNS requests.
437     * The statistics are across all interfaces.
438     *
439     * {@see android.os.Process#myUid()}.
440     *
441     * @param uid The UID of the process to examine.
442     * @return number of packets.  If the statistics are not supported by this device,
443     * {@link #UNSUPPORTED} will be returned.
444     */
445    public static native long getUidUdpTxPackets(int uid);
446
447    /**
448     * Get the number of UDP packets received for this UID.
449     * Includes DNS responses.
450     * The statistics are across all interfaces.
451     *
452     * {@see android.os.Process#myUid()}.
453     *
454     * @param uid The UID of the process to examine.
455     * @return number of packets.  If the statistics are not supported by this device,
456     * {@link #UNSUPPORTED} will be returned.
457     */
458    public static native long getUidUdpRxPackets(int uid);
459
460    /**
461     * Return detailed {@link NetworkStats} for the current UID. Requires no
462     * special permission.
463     */
464    private static NetworkStats getNetworkStatsForUid(Context context) {
465        final IBinder binder = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
466        final INetworkManagementService service = INetworkManagementService.Stub.asInterface(
467                binder);
468
469        final int uid = android.os.Process.myUid();
470        try {
471            return service.getNetworkStatsUidDetail(uid);
472        } catch (RemoteException e) {
473            throw new RuntimeException(e);
474        }
475    }
476}
477