I would like to build an app that can track how long a user spends on certain apps (mainly for proof of concept and to implement in other apps.) I know that Lollipop implemented the API UsageStatsManager that enables you to track the "total length of time an app was in the foreground for a time interval (by day, week, month, or year)."
I have also read that one can poll the AcvtivtyManager continuously, however that would waste battery life and take up CPU and RAM.
What I am wonder is, is there an efficient way to keep track of the amount of time an app is open on devices running an android version lower than Lollipop. Specifically how apps like Aptrax and App Usage Tracker as well as many others, do it with very little or "No battery drain (even on high frequency tracking)." Is there another method that these apps use, to get app usage data on pre-Lollipop devices, with little battery usage, or is polling the Activity manger not as resource heavy as they source I read lead me to believe.
Tap "Battery Usage." 3. Make sure you're on the App tab. You can scroll through the list of apps on your phone and see what percentage of the total battery each of your apps is currently using.
android.app.usage.UsageStatsManager. Provides access to device usage history and statistics. Usage data is aggregated into time intervals: days, weeks, months, and years.
Android keeps a log of when an app (it's component) was last used. You can head down to /data/system/usagestats/ using a file explorer with root access, or using adb. There would be a file named usage-history.
i have tried to do the same but found no better way, basicklly poll the activity manager, now to make sure not to waste battary use the alarmManager and a recieverto set the waking times of the pollin so that when the phone is asleep it wont be woken for your poll (assume that user uses apps when the screen is on and phone is active) and poll like every 5 seconds or so here is basic sample code
Intent alarmIntent = new Intent(context, MyReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, Calendar.getInstance().getTimeInMillis(), pendingIntent);
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, Intent intent) {
// poll activity manager and any thing else you want here
// including figuring out the next time you want to run
// and scheduling another PendingIntent with the AlarmManager
}
}
using AlarmManager.RTC makes sure the reciever is only polling when the phone is awake.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With