在Lollipop前设备上跟踪Android上的每个应用程序使用情况

Nei*_* M. 6 android

我想构建一个应用程序,可以跟踪用户在某些应用程序上花费多长时间(主要用于概念验证和在其他应用程序中实现.)我知道Lollipop实现了API UsageStatsManager,使您能够跟踪"总长度应用程序在前景中的时间间隔(按天,周,月或年)."

我还读到可以连续轮询AcvtivtyManager,但这会浪费电池寿命并占用CPU和RAM.

我不知道的是,有没有一种有效的方法来跟踪运行Android版本低于Lollipop的设备上的应用程序打开的时间.特别是像AptraxApp Usage Tracker这样的应用程序以及其他许多应用程序,只需很少或"没有电池消耗(即使在高频跟踪下)".这些应用程序是否使用了另一种方法,在Lollipop之前的设备上获取应用程序使用数据,电池使用量很少,或者调查活动管理器的资源不是因为它们来源我认为引导我相信.

Gab*_*l H 3

我尝试过做同样的事情,但没有找到更好的方法,基本上轮询活动管理器,现在确保不浪费电池,使用alarmManager和接收器设置轮询的唤醒时间,这样当手机处于睡眠状态时,它就不会被浪费。唤醒您的民意调查(假设用户在屏幕打开且手机处于活动状态时使用应用程序)并每隔 5 秒左右进行一次民意调查,这里是基本示例代码

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
    }
}
Run Code Online (Sandbox Code Playgroud)

使用 AlarmManager.RTC 确保接收器仅在手机唤醒时进行轮询。