Reputation: 41
The below code tracks todays usage of an app every second to get accurate usage time. The issue is it logs the same usage time every second, which is the usage time when the app was opened. The usage time does not change until the user reopens the app. The usage time should increase while I am using the app but it does not, how I can get live usage time of that app.
Handler handler = new Handler(getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
long currentTime = System.currentTimeMillis();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
long startMillis = calendar.getTimeInMillis();
UsageStatsManager usageStatsManager = (UsageStatsManager) getSystemService(Context.USAGE_STATS_SERVICE);
List<UsageStats> usageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY,startMillis, currentTime);
for(UsageStats stat : usageStats){
if(stat.getPackageName().equals(getPackageName())){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
Log.d("MainActivity", "Usage time: " + stat.getTotalTimeVisible());
}
}
}
handler.postDelayed(this, 1000);
}
});
Heres the log while using the app(does not change if the app is running in foreground):
2024-02-25 17:30:22.840 13942-13942 MainActivity com.prototype1 D Usage time: 1435719
2024-02-25 17:30:23.851 13942-13942 MainActivity com.prototype1 D Usage time: 1435719
2024-02-25 17:30:24.864 13942-13942 MainActivity com.prototype1 D Usage time: 1435719
2024-02-25 17:30:25.874 13942-13942 MainActivity com.prototype1 D Usage time: 1435719
2024-02-25 17:30:26.885 13942-13942 MainActivity com.prototype1 D Usage time: 1435719
2024-02-25 17:30:27.894 13942-13942 MainActivity com.prototype1 D Usage time: 1435719
2024-02-25 17:30:28.906 13942-13942 MainActivity com.prototype1 D Usage time: 1435719
2024-02-25 17:30:29.916 13942-13942 MainActivity com.prototype1 D Usage time: 1435719
Upvotes: -1
Views: 518
Reputation: 6160
Even though you're polling getTotalTimeVisible
every second, the time interval that you provide to queryUsageStats
method through beginTime
and endTime
parameters is always the same (and refers to the past).
Because of that, the getTotalTimeVisible
method call will always give you back the same value.
Upvotes: 0