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周的時間,研究了這樣一套流量的監控,不足的地方,多多指教啊!