-1

I need to start a foreground service from my app based on a remote event. Most of time when this happens the user will be on the app and the app will be visible, but on a small amount of the time the user will be on a different app or the screen will be off.

So I want to have logic that decides on Android 8+ whether it should call startService or startForegroundService based on whether the app is on the background or not. So how can I know this?

Edit: I did see on another answer that you can just keep a flag for onPause and onResume but I was hoping there would be a better way by now?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
casolorz
  • 8,486
  • 19
  • 93
  • 200

1 Answers1

0

A Kotlin solution from Google I/O 2016

class YourApplication : Application() {

      override fun onCreate() {
        super.onCreate()
        registerActivityLifecycleCallbacks(AppLifecycleTracker())
      }

    }


    class AppLifecycleTracker : Application.ActivityLifecycleCallbacks  {

      private var numStarted = 0

      override fun onActivityStarted(activity: Activity?) {
        if (numStarted == 0) {
          // app went to foreground
        }
        numStarted++
      }

      override fun onActivityStopped(activity: Activity?) {
        numStarted--
        if (numStarted == 0) {
          // app went to background
        }
      }

    }
Rainmaker
  • 10,294
  • 9
  • 54
  • 89