8

I am trying to read when an app was last used using UsageStatsManager Class recently introduced in Android.

But there is a issue. it gives proper result for most of apps. but for some apps for call : appUsageStats.get(appInformation.packageName).getLastTimeUsed() it returns a 4 digit millisecond which is not correct.

Attached is a screen shot of evaluate window showing 8738 for true caller app. Is this a bug or am I doing something wrong?

enter image description here

Note: As an observation this API returns correct results when mLastTimeSystemUsed is same as mLastTimeUsed. Just an FYI.

Code snippet below:

Map<String, UsageStats> appUsageStats = UStats.getMapOfAggregatedUsage(MainActivity.this);

if(appUsageStats.get(appInformation.packageName)!=null) {
    long used = appUsageStats.get(appInformation.packageName).getLastTimeUsed();
    long installedDiff2 = new Date().getTime() - new Date(used).getTime();
    long daysGap = TimeUnit.DAYS.convert(installedDiff2, TimeUnit.MILLISECONDS);

    if(daysGap == 0) {
        appInfoObj.setAppUsedDate("Used : Today");
    } else {
        appInfoObj.setAppUsedDate("Used : " + String.valueOf(daysGap) + " days ago");

    }
    appInfoObj.setAppUsedDateNumber(daysGap);
}

UStats Class Method:

public static Map<String, UsageStats> getMapOfAggregatedUsage(Context context) {
    Calendar calendar = Calendar.getInstance();

    long endTime = calendar.getTimeInMillis();
    calendar.add(Calendar.YEAR, -1);
    long startTime = calendar.getTimeInMillis();
    return getUsageStatsManager(context).queryAndAggregateUsageStats(startTime,endTime);

   // return null;
}
aldok
  • 17,295
  • 5
  • 53
  • 64
sunil
  • 177
  • 2
  • 12
  • Upvoted because happens to me too. Btw, `mLastTimeSystemUsed` is no longer available. See: https://developer.android.com/reference/android/app/usage/UsageStats – aldok Jul 06 '21 at 05:02
  • Were you guys able to find a solution? For me lastTimeUsed and lastTimeVisible always coming 0 – priojeet priyom Apr 04 '23 at 20:49

0 Answers0