TrafficStats.java revision 8568db534118fc14cc28100306d51626464ff319
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     * @deprecated unsupported, will eventually be removed
101     */
102    @Deprecated
103    public static void setThreadStatsTag(String tag) {
104        setThreadStatsTag(tag.hashCode());
105    }
106
107    public static void clearThreadStatsTag() {
108        NetworkManagementSocketTagger.setThreadSocketStatsTag(-1);
109    }
110
111    /**
112     * Set specific UID to use when accounting {@link Socket} traffic
113     * originating from the current thread. Designed for use when performing an
114     * operation on behalf of another application.
115     * <p>
116     * Changes only take effect during subsequent calls to
117     * {@link #tagSocket(Socket)}.
118     * <p>
119     * To take effect, caller must hold
120     * {@link android.Manifest.permission#UPDATE_DEVICE_STATS} permission.
121     *
122     * {@hide}
123     */
124    public static void setThreadStatsUid(int uid) {
125        NetworkManagementSocketTagger.setThreadSocketStatsUid(uid);
126    }
127
128    /** {@hide} */
129    public static void clearThreadStatsUid() {
130        NetworkManagementSocketTagger.setThreadSocketStatsUid(-1);
131    }
132
133    /**
134     * Tag the given {@link Socket} with any statistics parameters active for
135     * the current thread. Subsequent calls always replace any existing
136     * parameters. When finished, call {@link #untagSocket(Socket)} to remove
137     * statistics parameters.
138     *
139     * @see #setThreadStatsTag(int)
140     * @see #setThreadStatsUid(int)
141     */
142    public static void tagSocket(Socket socket) throws SocketException {
143        SocketTagger.get().tag(socket);
144    }
145
146    /**
147     * Remove any statistics parameters from the given {@link Socket}.
148     */
149    public static void untagSocket(Socket socket) throws SocketException {
150        SocketTagger.get().untag(socket);
151    }
152
153    /**
154     * Start profiling data usage for current UID. Only one profiling session
155     * can be active at a time.
156     *
157     * @hide
158     */
159    public static void startDataProfiling(Context context) {
160        synchronized (sProfilingLock) {
161            if (sActiveProfilingStart != null) {
162                throw new IllegalStateException("already profiling data");
163            }
164
165            // take snapshot in time; we calculate delta later
166            sActiveProfilingStart = getNetworkStatsForUid(context);
167        }
168    }
169
170    /**
171     * Stop profiling data usage for current UID.
172     *
173     * @return Detailed {@link NetworkStats} of data that occurred since last
174     *         {@link #startDataProfiling(Context)} call.
175     * @hide
176     */
177    public static NetworkStats stopDataProfiling(Context context) {
178        synchronized (sProfilingLock) {
179            if (sActiveProfilingStart == null) {
180                throw new IllegalStateException("not profiling data");
181            }
182
183            // subtract starting values and return delta
184            final NetworkStats profilingStop = getNetworkStatsForUid(context);
185            final NetworkStats profilingDelta = profilingStop.subtractClamped(
186                    sActiveProfilingStart);
187            sActiveProfilingStart = null;
188            return profilingDelta;
189        }
190    }
191
192    /**
193     * Get the total number of packets transmitted through the mobile interface.
194     *
195     * @return number of packets.  If the statistics are not supported by this device,
196     * {@link #UNSUPPORTED} will be returned.
197     */
198    public static native long getMobileTxPackets();
199
200    /**
201     * Get the total number of packets received through the mobile interface.
202     *
203     * @return number of packets.  If the statistics are not supported by this device,
204     * {@link #UNSUPPORTED} will be returned.
205     */
206    public static native long getMobileRxPackets();
207
208    /**
209     * Get the total number of bytes transmitted through the mobile interface.
210     *
211     * @return number of bytes.  If the statistics are not supported by this device,
212     * {@link #UNSUPPORTED} will be returned.
213     */
214      public static native long getMobileTxBytes();
215
216    /**
217     * Get the total number of bytes received through the mobile interface.
218     *
219     * @return number of bytes.  If the statistics are not supported by this device,
220     * {@link #UNSUPPORTED} will be returned.
221     */
222    public static native long getMobileRxBytes();
223
224    /**
225     * Get the total number of packets transmitted through the specified interface.
226     *
227     * @return number of packets.  If the statistics are not supported by this interface,
228     * {@link #UNSUPPORTED} will be returned.
229     * @hide
230     */
231    public static native long getTxPackets(String iface);
232
233    /**
234     * Get the total number of packets received 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 getRxPackets(String iface);
241
242    /**
243     * Get the total number of bytes transmitted through the specified interface.
244     *
245     * @return number of bytes.  If the statistics are not supported by this interface,
246     * {@link #UNSUPPORTED} will be returned.
247     * @hide
248     */
249    public static native long getTxBytes(String iface);
250
251    /**
252     * Get the total number of bytes received 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 getRxBytes(String iface);
259
260
261    /**
262     * Get the total number of packets sent through all network interfaces.
263     *
264     * @return the number of packets.  If the statistics are not supported by this device,
265     * {@link #UNSUPPORTED} will be returned.
266     */
267    public static native long getTotalTxPackets();
268
269    /**
270     * Get the total number of packets received through all network interfaces.
271     *
272     * @return number of packets.  If the statistics are not supported by this device,
273     * {@link #UNSUPPORTED} will be returned.
274     */
275    public static native long getTotalRxPackets();
276
277    /**
278     * Get the total number of bytes sent through all network interfaces.
279     *
280     * @return number of bytes.  If the statistics are not supported by this device,
281     * {@link #UNSUPPORTED} will be returned.
282     */
283    public static native long getTotalTxBytes();
284
285    /**
286     * Get the total number of bytes received through all network interfaces.
287     *
288     * @return number of bytes.  If the statistics are not supported by this device,
289     * {@link #UNSUPPORTED} will be returned.
290     */
291    public static native long getTotalRxBytes();
292
293    /**
294     * Get the number of bytes sent through the network for this UID.
295     * The statistics are across all interfaces.
296     *
297     * {@see android.os.Process#myUid()}.
298     *
299     * @param uid The UID of the process to examine.
300     * @return number of bytes.  If the statistics are not supported by this device,
301     * {@link #UNSUPPORTED} will be returned.
302     */
303    public static native long getUidTxBytes(int uid);
304
305    /**
306     * Get the number of bytes received through the network for this UID.
307     * The statistics are across all interfaces.
308     *
309     * {@see android.os.Process#myUid()}.
310     *
311     * @param uid The UID of the process to examine.
312     * @return number of bytes
313     */
314    public static native long getUidRxBytes(int uid);
315
316    /**
317     * Get the number of packets (TCP segments + UDP) sent through
318     * the network for this UID.
319     * The statistics are across all interfaces.
320     *
321     * {@see android.os.Process#myUid()}.
322     *
323     * @param uid The UID of the process to examine.
324     * @return number of packets.
325     * If the statistics are not supported by this device,
326     * {@link #UNSUPPORTED} will be returned.
327     */
328    public static native long getUidTxPackets(int uid);
329
330    /**
331     * Get the number of packets (TCP segments + UDP) received through
332     * the network for this UID.
333     * The statistics are across all interfaces.
334     *
335     * {@see android.os.Process#myUid()}.
336     *
337     * @param uid The UID of the process to examine.
338     * @return number of packets
339     */
340    public static native long getUidRxPackets(int uid);
341
342    /**
343     * Get the number of TCP payload bytes sent for this UID.
344     * This total does not include protocol and control overheads at
345     * the transport and the lower layers of the networking stack.
346     * The statistics are across all interfaces.
347     *
348     * {@see android.os.Process#myUid()}.
349     *
350     * @param uid The UID of the process to examine.
351     * @return number of bytes.  If the statistics are not supported by this device,
352     * {@link #UNSUPPORTED} will be returned.
353     */
354    public static native long getUidTcpTxBytes(int uid);
355
356    /**
357     * Get the number of TCP payload bytes received for this UID.
358     * This total does not include protocol and control overheads at
359     * the transport and the lower layers of the networking stack.
360     * The statistics are across all interfaces.
361     *
362     * {@see android.os.Process#myUid()}.
363     *
364     * @param uid The UID of the process to examine.
365     * @return number of bytes.  If the statistics are not supported by this device,
366     * {@link #UNSUPPORTED} will be returned.
367     */
368    public static native long getUidTcpRxBytes(int uid);
369
370    /**
371     * Get the number of UDP payload bytes sent for this UID.
372     * This total does not include protocol and control overheads at
373     * the transport and the lower layers of the networking stack.
374     * The statistics are across all interfaces.
375     *
376     * {@see android.os.Process#myUid()}.
377     *
378     * @param uid The UID of the process to examine.
379     * @return number of bytes.  If the statistics are not supported by this device,
380     * {@link #UNSUPPORTED} will be returned.
381     */
382    public static native long getUidUdpTxBytes(int uid);
383
384    /**
385     * Get the number of UDP payload bytes received for this UID.
386     * This total does not include protocol and control overheads at
387     * the transport and the lower layers of the networking stack.
388     * The statistics are across all interfaces.
389     *
390     * {@see android.os.Process#myUid()}.
391     *
392     * @param uid The UID of the process to examine.
393     * @return number of bytes.  If the statistics are not supported by this device,
394     * {@link #UNSUPPORTED} will be returned.
395     */
396    public static native long getUidUdpRxBytes(int uid);
397
398    /**
399     * Get the number of TCP segments sent for this UID.
400     * Does not include TCP control packets (SYN/ACKs/FIN/..).
401     * The statistics are across all interfaces.
402     *
403     * {@see android.os.Process#myUid()}.
404     *
405     * @param uid The UID of the process to examine.
406     * @return number of TCP segments.  If the statistics are not supported by this device,
407     * {@link #UNSUPPORTED} will be returned.
408     */
409    public static native long getUidTcpTxSegments(int uid);
410
411    /**
412     * Get the number of TCP segments received for this UID.
413     * Does not include TCP control packets (SYN/ACKs/FIN/..).
414     * The statistics are across all interfaces.
415     *
416     * {@see android.os.Process#myUid()}.
417     *
418     * @param uid The UID of the process to examine.
419     * @return number of TCP segments.  If the statistics are not supported by this device,
420     * {@link #UNSUPPORTED} will be returned.
421     */
422    public static native long getUidTcpRxSegments(int uid);
423
424
425    /**
426     * Get the number of UDP packets sent for this UID.
427     * Includes DNS requests.
428     * The statistics are across all interfaces.
429     *
430     * {@see android.os.Process#myUid()}.
431     *
432     * @param uid The UID of the process to examine.
433     * @return number of packets.  If the statistics are not supported by this device,
434     * {@link #UNSUPPORTED} will be returned.
435     */
436    public static native long getUidUdpTxPackets(int uid);
437
438    /**
439     * Get the number of UDP packets received for this UID.
440     * Includes DNS responses.
441     * The statistics are across all interfaces.
442     *
443     * {@see android.os.Process#myUid()}.
444     *
445     * @param uid The UID of the process to examine.
446     * @return number of packets.  If the statistics are not supported by this device,
447     * {@link #UNSUPPORTED} will be returned.
448     */
449    public static native long getUidUdpRxPackets(int uid);
450
451    /**
452     * Return detailed {@link NetworkStats} for the current UID. Requires no
453     * special permission.
454     */
455    private static NetworkStats getNetworkStatsForUid(Context context) {
456        final IBinder binder = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
457        final INetworkManagementService service = INetworkManagementService.Stub.asInterface(
458                binder);
459
460        final int uid = android.os.Process.myUid();
461        try {
462            return service.getNetworkStatsUidDetail(uid);
463        } catch (RemoteException e) {
464            throw new RuntimeException(e);
465        }
466    }
467}
468