How to count app usage time while app is on foreground?

前端 未结 1 1171
梦谈多话
梦谈多话 2020-11-30 13:29

I\'m working on an android app for tracking daily app usage. The idea is that a user can set daily time limit for any app and a notification will appear within at most 2 min

相关标签:
1条回答
  • 2020-11-30 13:32

    I've solved the issue.

    Adding difference of current time and timestamp of current running app going foreground does the trick.

    I just added the following code before the return statement:

    UsageEvents.Event lastEvent = allEvents.get(allEvents.size() - 1);
    if(lastEvent.getEventType() == UsageEvents.Event.ACTIVITY_RESUMED) {
        int diff = (int)System.currentTimeMillis() - (int)lastEvent.getTimeStamp();
        diff /= 1000;
        Integer prev = appUsageMap.get(lastEvent.getPackageName());
        if(prev == null) prev = 0;
        appUsageMap.put(lastEvent.getPackageName(), prev + diff);
    }
    

    It is pretty straightforward, I should have thought about it before posting the question.

    0 讨论(0)
提交回复
热议问题