今天找到一个关于获取网络流量不错的资料:

在Android2.2以后,官网已经提供了获取手机网络流量的类:

TrafficStatshttp://developer.android.com/reference/android/net/TrafficStats.html

但是,或许这个类并不能满足要求或者你的Android版本低于2.2。那么可以尝试以下方法。

从系统文件中读取。下面是一直TrafficStats与系统文件的对应表。(其实官方给的API TrafficStats也是从以下文件读取


Android 获取手机流量

下面是一段代码的范例:

import java.io.FileNotFoundException;import java.io.IOException;import java.io.RandomAccessFile;import android.util.Log;public class TrafficStatsFile {private static final String mobileRxFile_1 = "/sys/class/net/rmnet0/statistics/rx_bytes";private static final String mobileRxFile_2 = "/sys/class/net/ppp0/statistics/rx_bytes";private static final String mobileTxFile_1 = "/sys/class/net/rmnet0/statistics/tx_bytes";private static final String mobileTxFile_2 = "/sys/class/net/ppp0/statistics/tx_bytes";private static final String LOGGING_TAG = TrafficStatsFile.class.getSimpleName();public long getMobileRxBytes() {    return tryBoth(mobileRxFile_1, mobileRxFile_2);}public long getMobileTxBytes() {    return tryBoth(mobileTxFile_1, mobileTxFile_2);}// Return the number from the first file which exists and contains dataprivate static long tryBoth(String a, String b) {    long num = readNumber(a);    return num >= 0 ? num : readNumber(b);}// Returns an ASCII decimal number read from the specified file, -1 on error.private static long readNumber(String filename) {    try {        RandomAccessFile f = new RandomAccessFile(filename, "r");        try {            Log.d(LOGGING_TAG, "f.length() = " + f.length());            String contents = f.readLine();            if(!contents.isEmpty() && contents!=null) {                try {                    return Long.parseLong(contents);                }                catch(NumberFormatException nfex) {                    Log.w(LOGGING_TAG, "File contents are not numeric: " + filename);                 }            }            else {                Log.w(LOGGING_TAG, "File contents are empty: " + filename);             }        }        catch (FileNotFoundException fnfex) {            Log.w(LOGGING_TAG, "File not found: " + filename, fnfex);        }        catch(IOException ioex) {            Log.w(LOGGING_TAG, "IOException: " + filename, ioex);        }       }catch(FileNotFoundException ffe){        Log.w(LOGGING_TAG, "File not found: " + filename, ffe);    }    return -1;}}

更多相关文章

  1. Android开发之文件下载
  2. 解决android中使用shape文件画虚线不显示
  3. AndroidManifest.xml文件剖析 (二)
  4. 第15章 Android启动过程 [Android应用开发与系统改造实战]
  5. 帮同事找到了一个问题的解决办法:在android 3.0版本以上的系统 we
  6. android中使用sqlite、复制assets下的数据库到SD卡、支持大于1M
  7. 2015Android设备、系统、分辨率最新统计数据
  8. Android的参数大致分成两块:系统服务参数和平台系统信息。

随机推荐

  1. Android(安卓)中的ANR 问题,响应灵敏性
  2. Android智能硬件开发心得总结(一)
  3. Linux 环境下Android(安卓)Tcpdump 抓取
  4. Android 版 Instagram 正式推出!
  5. android 资源文件学习
  6. Android UI 之TextView控件中可选择的属
  7. Android基础入门知识
  8. Android Bmob后端云—数据库、服务器!
  9. android 网络数据抓包
  10. Android零基础入门第16节:Android用户界面