I am trying to get the power consumption details made by each installed app in a list. But since I do not have root access, I know I won't be able to use adb
shell commands to get battery usage info for all processes.
What I think I can do is get the uptime for each installed app, get the total time my battery has been disconnected (by saving timestamp when ACTION_POWER_DISCONNECTED
happens), and calculating -
( app_runtime * 100 ) / total_time_battery_disconnected
However, I am unable to obtain the most basic info about an app -> how long it has been running ? I can use activeSince on RunningServices, but that is not the solution here.
The class ApplicationInfo
does not provide any such methods either.
Is there any way to get this detail ? I see so many bloatware apps showing my the total consumption made by every app I have installed with the running since time also shown, so I know it is possible. But how ?
I looked into this article on Android Battery Life. But this is limited to Android internals.
Even tried UsageStats, but its not working, returning Zero when querying usage stats list.
The UsageStatsManager should do what you are asking for. Not sure why it's not working, perhaps you need this in your manifest?
<uses-permission
android:name="android.permission.PACKAGE_USAGE_STATS"
tools:ignore="ProtectedPermissions" />
Here's a sample logging the UsageStats
long startTime = new GregorianCalendar(2016, 0, 1).getTimeInMillis();
long endTime = new GregorianCalendar(2017, 0, 1).getTimeInMillis();
UsageStatsManager usageStatsManager = (UsageStatsManager)context.getSystemService(Context.USAGE_STATS_SERVICE);
List<UsageStats> queryUsageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, startTime, endTime);
for (UsageStats us : queryUsageStats) {
Log.d(TAG, us.getPackageName() + " = " + us.getTotalTimeInForeground());
}
This page has an example that walks you through the process of getting the persmission from the user. Lastly, here a full sample on GitHub.
Prior to API 21 - The SDK does not provide a mechanism to get application usage statistics. The only way to do it would be to poll the ActivityManager using the getRunningTasks or getRecentTasks functions. I'll direct you to CommonsWare's response to a similar question.