Android 获取手机流量
2013-11-07 00:00
316 查看
今天找到一个关于获取网络流量不错的资料:
在Android2.2以后,官网已经提供了获取手机网络流量的类:
TrafficStats :http://developer.android.com/reference/android/net/TrafficStats.html
但是,或许这个类并不能满足要求或者你的Android版本低于2.2。那么可以尝试以下方法。
从系统文件中读取。下面是一直TrafficStats与系统文件的对应表。(其实官方给的API TrafficStats也是从以下文件读取)
下面是一段代码的范例:
在Android2.2以后,官网已经提供了获取手机网络流量的类:
TrafficStats :http://developer.android.com/reference/android/net/TrafficStats.html
但是,或许这个类并不能满足要求或者你的Android版本低于2.2。那么可以尝试以下方法。
从系统文件中读取。下面是一直TrafficStats与系统文件的对应表。(其实官方给的API TrafficStats也是从以下文件读取)
下面是一段代码的范例:
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 data private 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; } }
相关文章推荐
- Android 获取 Wifi 信号强度,检测是 Wifi 或者流量,获取手机电池电量及充电状态
- android获取手机流量使用情况
- android 2.1 获取手机流量
- Android 获取手机整体流量使用情况以及某个应用的流量的统计
- Android 获取 Wifi 信号强度,检测是 Wifi 或者流量,获取手机电池电量及充电状态
- android获取手机流量使用情况
- Android 使用CursorLoader获取手机短信
- Android获取手机号码及运营商
- android获取手机的国家码
- Android手机用户隐私获取,包括读取通讯录、读取通话记录、读取浏览器历史记录、读取手机短信
- android获取手机录
- android获取本机号码,版本号,手机型号
- Android 在代码中获取手机屏幕的宽高
- 【Android基础 005】 Android获取手机和系统版本等信息
- 怎么用代码判断Android手机的Rom是MIUI及获取MIUI版本
- android 获取手机设备品牌
- android获取手机屏幕宽和高
- android 如何获取手机的图片、视频、音乐
- Android简易实战教程--第十二话《代码获取手机总运行内存的大小》
- 如何获取Android手机底部导航栏的高度