0

I have an application that keeps tracks of other applications screentime. I have a service which is supposed to give a notification after the user has spend X time on a specific application. To keep track of other applications, I have used a Service. When my own application is open, the details of other applications screen time is shown correctly, but when my app goes in the background, the details aren't updated (they remain the same as when my own application was open), but as soon as I reopen my application, the details get updated. Why isnt the UsageStatsManager working properly while being in the background?

        var appList = usm.queryUsageStats(
            UsageStatsManager.INTERVAL_DAILY,
            System.currentTimeMillis() - 1000 * 3600 * 24,
            System.currentTimeMillis()
        )

I have the following code in my manifest

    <uses-permission android:name="android.permission.PACKAGE_USAGE_STATS"
        tools:ignore="ProtectedPermissions" />
        <service android:enabled="true" android:name=".MyService" />
    </application>
Ammar Ahsan
  • 83
  • 1
  • 9
  • Are you using a foreground service or background service. – Nitish Sep 08 '21 at 10:39
  • @NitishChaudhary Background Service – Ammar Ahsan Sep 08 '21 at 10:42
  • Background services only runs when app is open. When app goes in background, services are stopped. To run service when app in background you need to switch to foreground service [link](https://medium.com/@jayd1992/foreground-services-in-android-e131a863a33d) – Nitish Sep 08 '21 at 10:44
  • "but when my app goes in the background, the details aren't updated" -- a background service only runs for about a minute before being stopped on Android 8 and higher. – CommonsWare Sep 08 '21 at 10:46
  • Changed it to foreground service, but it still isnt updating the screen time for different applications. – Ammar Ahsan Sep 08 '21 at 10:56
  • How often does the UsageStatsManager update the details about the applications? Does it only update the screen time once the application has been closed? – Ammar Ahsan Sep 08 '21 at 11:55

1 Answers1

1

UsageStatsManager doesn't update the unless the app goes in background. You can archive this by adding the difference of current time and timestamp of current running app going foreground.
Refer to this answer for details : How to count app usage time while app is on foreground?

Nitish
  • 3,075
  • 3
  • 13
  • 28