问题
I'm trying to get the mobile data used by all application in previous month( or week) or between a given time period. I want to get the mobile data usage history. I see that android is doing this by default now. Is it possible to get this information by code?
回答1:
Is it possible to get this information by code?
Not in any documented or supported fashion, at least through Android 4.4. You are welcome to collect this data yourself by periodically examining TrafficStats, though.
回答2:
Try this code
public void getPakagesInfoUsingHashMap() {
final PackageManager pm = getPackageManager();
// get a list of installed apps.
List<ApplicationInfo> packages = pm.getInstalledApplications(0);
// loop through the list of installed packages and see if the selected
// app is in the list
for (ApplicationInfo packageInfo : packages) {
// get the UID for the selected app
UID = packageInfo.uid;
String package_name = packageInfo.packageName;
ApplicationInfo app = null;
try {
app = pm.getApplicationInfo(package_name, 0);
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String name = (String) pm.getApplicationLabel(app);
Drawable icon = pm.getApplicationIcon(app);
// internet usage for particular app(sent and received)
double received = (double) TrafficStats.getUidRxBytes(UID)
/ (1024 * 1024);
double send = (double) TrafficStats.getUidTxBytes(UID)
/ (1024 * 1024);
double total = received + send;
if(total>0)
{
PackageInformationTotal pi=new PackageInformationTotal();
pi.name=name;
pi.packageName=package_name;
pi.icon=icon;
pi.totalMB=String.format( "%.2f", total )+" MB";
pi.individual_mb=String.format( "%.2f", total );
totalData+=Double.parseDouble(String.format( "%.2f", total ));
dataHash.add(pi);
Log.e(name,String.format( "%.2f", total )+" MB");
}
}
Editor edit=shared.edit();
edit.putString("Total",String.format( "%.2f", totalData));
edit.commit();
}
The following links should help you figure out how to programatically detemrine the data usage per application.
https://github.com/commonsguy/cw-andtuning/tree/master/TrafficMonitor
http://www.techrepublic.com/blog/app-builder/create-a-network-monitor-using-androids-trafficstats-class/774
http://agolovatyuk.blogspot.com/2012/04/android-traffic-statistics-inside.html
You will need to implement your code to use the TraficStats API and track the number of bytes sent/received per UID (application).
来源:https://stackoverflow.com/questions/25230390/how-to-get-the-stats-of-total-mobile-data-used-in-give-time-periodeg-last-mont