1,开启一个服务,每5分钟跑动一次更新流量,用于能够准确记录流量
每一个小时,更新一次流量,用于清除非本月的流量
2,保存流量的时候,进行判断
a,若是数据库中保存的 旧流量oldFlow > 文件流量newFlow,说明手机重启过, 保存流量 = 前一次数据库保存流量 + 文件流量
b,若是数据库中保存的 旧流量oldFlow <= 文件流量newFlow,说明软件消耗了新量,保存流量=oldFlow-newFlow+前一次数据库保存流量
/**
* 获取每个应用的流量信息
*/
public List<FlowInfo> getGPRSData() {
List<FlowInfo> uidList = new ArrayList<FlowInfo>();
PackageManager pm = context.getPackageManager();
List<PackageInfo> packinfos = pm
.getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES
| PackageManager.GET_PERMISSIONS);
long newFlow = 0;
long[] oldStandardFlow = null;
String date = TimeUtil.getInstance().getStringDate();
for (PackageInfo info : packinfos) {
FlowInfo uidInfo = new FlowInfo();
String[] premissions = info.requestedPermissions;
if (premissions != null && premissions.length > 0) {
for (String premission : premissions) {
if ("android.permission.INTERNET".equals(premission)) {
int uid = info.applicationInfo.uid;
uidInfo.setUid(uid);
newFlow = Long.valueOf(getSndFlowByUid(uid))
+ Long.valueOf(getRcvFlowByUid(uid));
tableHelp = TableHelp.getInstance(context,
"FlowMonitors.db", 1);
sqlite = tableHelp.getSqliteDatabase();
oldStandardFlow = tableHelp.getOldStandardFlow(sqlite, uid, date); // 保存的旧流量和标准流量
if (oldStandardFlow[0] > newFlow) { // 旧流量和文件中的新流量对比,旧流量较大说明重启了手机,要保存的流量=文件流量+标准流量,旧流量保存为文件流量
uidInfo.setOldFlow(newFlow);
newFlow = oldStandardFlow[1] + newFlow;
uidInfo.setFlow(newFlow);
} else { //若是文件流量大于旧流量,则标准流量=文件流量-旧流量 + 原始标准流量,旧流量保存为新流量
uidInfo.setOldFlow(newFlow);
newFlow = newFlow - oldStandardFlow[0] + oldStandardFlow[1];
uidInfo.setFlow(newFlow);
}
uidInfo.setDate(date);
uidList.add(uidInfo);
}
}
}
}
return uidList;
}
花了1,2周的时间,研究了这样一套流量的监控,不足的地方,多多指教啊!