Home > Software engineering >  How can I observe an other apps launch?
How can I observe an other apps launch?

Time:01-02

For a mental health app project, I need to intercept the startup of specific apps (like Instagram) and check if they used instagram the n-th time, possibly opening a questionair etc.

Searching for a solutions online, I came across the "android.app.usage" API. I could not get my around how to use this. Do I need a for every running background service which does active polling with the usage api? Or is their a way to say "run this code or start this app/service when appXY launches"?

Looking forward to any kind of input :)

Greetings Pascal

CodePudding user response:

You can't listen out for an "app is being opened" intent unfortunately, Android doesn't support it. Your approach is likely the best workaround, to state it explicitly:

  1. Have a foreground service running (so it is less likely to be killed by the OS) at all times.
  2. Check regularly the currently running app, and see if it's the one you're trying to look for.
  3. If this is different to last time you checked, do whatever you need to. Perhaps this will include keeping track of last time the app was opened, how many times it's been opened etc.

As a warning however, the OS won't really like this, and there's likely to be an impact on battery life. Whatever you do, make sure this check isn't happening when the screen is off, happening as infrequently as possible, and doesn't include any unnecessary computation, otherwise the user will quickly notice the negative impact.

Here's an extract from an article that looks like it'll be able to fetch the latest app even on later versions:

var foregroundAppPackageName : String? = null
val currentTime = System.currentTimeMillis()
// The `queryEvents` method takes in the `beginTime` and `endTime` to retrieve the usage events.
// In our case, beginTime = currentTime - 10 minutes ( 1000 * 60 * 10 milliseconds )
// and endTime = currentTime
val usageEvents = usageStatsManager.queryEvents( currentTime - (1000*60*10) , currentTime )
val usageEvent = UsageEvents.Event()
while ( usageEvents.hasNextEvent() ) {
    usageEvents.getNextEvent( usageEvent )
    Log.e( "APP" , "${usageEvent.packageName} ${usageEvent.timeStamp}" )
}
  • Related