Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 464
Riccoh Avatar asked Jan 20 '26 09:01

Riccoh


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)
        ....
    }
}
like image 87
Juan Fraga Avatar answered Jan 22 '26 23:01

Juan Fraga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!