Search code examples
androidusagestatsmanager

How do I track app usage time in android?


I have been searched for a long times, but I cannot solve this.

I am developing app usage appplication, and I want to make user can restrict app usage time.

lets say user want to restrict Youtube app usage time for 10 min.

1. How can I make notification or toaster when Youtube app usage reach 10 min since user click button?(I know event handling)

  1. can I make observer even my app goes backgroud? or even after detroyed?

Base on my search registerAppUsageObserver looks like what I want to, but I cannot use it since its @hide

 public void registerAppUsageObserver(int observerId, @NonNull String[] observedEntities,
                long timeLimit, @NonNull TimeUnit timeUnit, @NonNull PendingIntent callbackIntent)

I can try to use it by reflection but I think its not recommended.

I got one more good source link but I don't know how to use it.

please help me. thank you.


Solution

  • I've done a fair bit of work in this area. I'd like to direct you to my smartCBT GitHub that reviews in a given period of time what a person has been using their apps for (https://github.com/kris-geyer/smartCBT; in particular, check out https://github.com/kris-geyer/smartCBT/blob/master/app/src/main/java/kg/own/smartcbt/ViewModel/RetrieveUsageRecords.java).

    First off, I wouldn't trust the usage stats manager. It's been very unreliable in the past for me. I think what you want to assess usage is usage events (https://developer.android.com/reference/android/app/usage/UsageEvents.Event). These give you a much more fine-grained account of android app usage which seem much more accurate. You will need to get special permission for this. I've actually, empirically tested the accuracy before and it is very high.

    For the overall structure of what your app needs I think you want a foreground service that runs in the background routinely logging what the person is using their phone for. This database is only updated when apps are changed, so handling this might be a little tricky but you'll manage.

    When the app has identified that the allotted amount of usage time for a particular app is up, then it can direct the user back to your app by launching a new activity from the foreground service. I'm not sure if this is still possible, the android permissions seem to change so quickly. What would be really cool is if you can get the app to play videos of the user telling themselves that they've used their phone too much and be productive.

    Best of luck. :)