2020import java .io .IOException ;
2121import java .io .RandomAccessFile ;
2222
23+ import android .net .TrafficStats ;
2324import android .util .Log ;
2425
2526/**
3031public class TrafficInfo {
3132
3233 private static final String LOG_TAG = "Emmagee-" + TrafficInfo .class .getSimpleName ();
34+ private static final int UNSUPPORTED = -1 ;
3335
3436 private String uid ;
3537
@@ -44,21 +46,34 @@ public TrafficInfo(String uid) {
4446 * @return total traffic include received and send traffic
4547 */
4648 public long getTrafficInfo () {
49+
4750 Log .i (LOG_TAG , "get traffic information" );
4851 Log .d (LOG_TAG , "uid===" + uid );
52+
53+ long rcvTraffic = UNSUPPORTED ;
54+ long sndTraffic = UNSUPPORTED ;
55+
56+ // Use getUidRxBytes and getUidTxBytes to get network traffic,these API
57+ // return both tcp and udp usage
58+ rcvTraffic = TrafficStats .getUidRxBytes (Integer .parseInt (uid ));
59+ sndTraffic = TrafficStats .getUidTxBytes (Integer .parseInt (uid ));
60+
61+ if (rcvTraffic == UNSUPPORTED || sndTraffic == UNSUPPORTED ) {
62+ return UNSUPPORTED ;
63+ }
64+
4965 RandomAccessFile rafRcv = null , rafSnd = null ;
5066 String rcvPath = "/proc/uid_stat/" + uid + "/tcp_rcv" ;
5167 String sndPath = "/proc/uid_stat/" + uid + "/tcp_snd" ;
52- long rcvTraffic = -1 ;
53- long sndTraffic = -1 ;
68+
5469 try {
5570 rafRcv = new RandomAccessFile (rcvPath , "r" );
5671 rafSnd = new RandomAccessFile (sndPath , "r" );
5772 rcvTraffic = Long .parseLong (rafRcv .readLine ());
5873 sndTraffic = Long .parseLong (rafSnd .readLine ());
5974 } catch (FileNotFoundException e ) {
60- rcvTraffic = - 1 ;
61- sndTraffic = - 1 ;
75+ rcvTraffic = UNSUPPORTED ;
76+ sndTraffic = UNSUPPORTED ;
6277 } catch (NumberFormatException e ) {
6378 Log .e (LOG_TAG , "NumberFormatException: " + e .getMessage ());
6479 e .printStackTrace ();
@@ -73,13 +88,12 @@ public long getTrafficInfo() {
7388 if (rafSnd != null )
7489 rafSnd .close ();
7590 } catch (IOException e ) {
76- Log .i (LOG_TAG , "close randomAccessFile exception: " + e .getMessage ());
91+ Log .w (LOG_TAG , "Close randomAccessFile exception: " + e .getMessage ());
7792 }
7893 }
79- Log .d (LOG_TAG , "rcvTraffic===" + rcvTraffic );
80- Log .d (LOG_TAG , "sndTraffic===" + sndTraffic );
81- if (rcvTraffic == -1 || sndTraffic == -1 ) {
82- return -1 ;
94+
95+ if (rcvTraffic == UNSUPPORTED || sndTraffic == UNSUPPORTED ) {
96+ return UNSUPPORTED ;
8397 } else
8498 return rcvTraffic + sndTraffic ;
8599 }
0 commit comments