|
16 | 16 | */
|
17 | 17 | package com.netease.qa.emmagee.utils;
|
18 | 18 |
|
| 19 | +import java.io.IOException; |
| 20 | +import java.io.RandomAccessFile; |
| 21 | + |
19 | 22 | import android.net.TrafficStats;
|
20 | 23 | import android.util.Log;
|
21 | 24 |
|
@@ -43,18 +46,52 @@ public TrafficInfo(String uid) {
|
43 | 46 | */
|
44 | 47 | public long getTrafficInfo() {
|
45 | 48 | Log.i(LOG_TAG, "get traffic information");
|
| 49 | + Log.d(LOG_TAG, "uid = " + uid); |
| 50 | + long traffic = trafficFromApi(); |
| 51 | + return traffic <= 0 ? trafficFromFiles() : traffic; |
| 52 | + } |
46 | 53 |
|
47 |
| - long rcvTraffic = UNSUPPORTED; |
48 |
| - long sndTraffic = UNSUPPORTED; |
49 |
| - |
50 |
| - // Use getUidRxBytes and getUidTxBytes to get network traffic,these API |
51 |
| - // return both tcp and udp usage |
| 54 | + /** |
| 55 | + * Use TrafficStats getUidRxBytes and getUidTxBytes to get network |
| 56 | + * traffic,these API return both tcp and udp usage |
| 57 | + * |
| 58 | + * @return |
| 59 | + */ |
| 60 | + private long trafficFromApi() { |
| 61 | + long rcvTraffic = UNSUPPORTED, sndTraffic = UNSUPPORTED; |
52 | 62 | rcvTraffic = TrafficStats.getUidRxBytes(Integer.parseInt(uid));
|
53 | 63 | sndTraffic = TrafficStats.getUidTxBytes(Integer.parseInt(uid));
|
| 64 | + return rcvTraffic + sndTraffic < 0 ? UNSUPPORTED : rcvTraffic + sndTraffic; |
| 65 | + } |
54 | 66 |
|
55 |
| - if (rcvTraffic == UNSUPPORTED || sndTraffic == UNSUPPORTED) { |
56 |
| - return UNSUPPORTED; |
57 |
| - } else |
58 |
| - return rcvTraffic + sndTraffic; |
| 67 | + /** |
| 68 | + * read files in uid_stat to get traffic info |
| 69 | + * |
| 70 | + * @return |
| 71 | + */ |
| 72 | + private long trafficFromFiles() { |
| 73 | + RandomAccessFile rafRcv = null, rafSnd = null; |
| 74 | + long rcvTraffic = UNSUPPORTED, sndTraffic = UNSUPPORTED; |
| 75 | + String rcvPath = "/proc/uid_stat/" + uid + "/tcp_rcv"; |
| 76 | + String sndPath = "/proc/uid_stat/" + uid + "/tcp_snd"; |
| 77 | + try { |
| 78 | + rafRcv = new RandomAccessFile(rcvPath, "r"); |
| 79 | + rafSnd = new RandomAccessFile(sndPath, "r"); |
| 80 | + rcvTraffic = Long.parseLong(rafRcv.readLine()); |
| 81 | + sndTraffic = Long.parseLong(rafSnd.readLine()); |
| 82 | + Log.d(LOG_TAG, String.format("rcvTraffic, sndTraffic = %s, %s", rcvTraffic, sndTraffic)); |
| 83 | + } catch (Exception e) { |
| 84 | + } |
| 85 | + finally { |
| 86 | + try { |
| 87 | + if (rafRcv != null) { |
| 88 | + rafRcv.close(); |
| 89 | + } |
| 90 | + if (rafSnd != null) |
| 91 | + rafSnd.close(); |
| 92 | + } catch (IOException e) {} |
| 93 | + } |
| 94 | + return rcvTraffic + sndTraffic < 0 ? UNSUPPORTED : rcvTraffic + sndTraffic; |
59 | 95 | }
|
| 96 | + |
60 | 97 | }
|
0 commit comments