How to check if app is on the foreground from Workmanager in BroadcastReceiver?

Viewed 619

Is there a way to check if app is in the background,closed or running from a Workmanager within BroadcastReceiver? I want to show an internal notification when the app is closed or in the background.

I already found some related topics about this but unfortunately the restrictions are changed since Android 10 which makes it a bit harder.

Thank you in advance

1 Answers

You could try something like that:

  1. Save current app state
class MyApplication : Application(), LifecycleObserver {

    private val sharedPreferences by lazy {
        PreferenceManager.getDefaultSharedPreferences(this)
    }

    override fun onCreate() {
        super.onCreate()
        ProcessLifecycleOwner.get().lifecycle.addObserver(this)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun onAppBackgrounded() {
        sharedPreferences.edit(commit = true) { putString("isAppOnForeground", false) }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onAppForegrounded() {
        sharedPreferences.edit(commit = true) { putString("isAppOnForeground", true) }
    }
}
  1. Fetch current state in your Work
class YourWorker constructor(
    private val context: Context,
    private val workParams: WorkerParameters
) : CoroutineWorker(context, workParams) {

    private val sharedPreferences by lazy {
        PreferenceManager.getDefaultSharedPreferences(context)
    }

    override suspend fun doWork(): Result {
        val isAppOnForeground = sharedPreferences.getBoolean("isAppOnForeground", false)
        ....
    }
}
Related