如何从 BroadcastReceiver 中的 Workmanager 检查应用程序是否在前台?

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

有没有办法通过 BroadcastReceiver 中的 Workmanager 检查应用程序是否在后台、关闭或 运行? 我想在应用关闭或在后台显示内部通知。

我已经找到了一些与此相关的主题,但不幸的是,自 Android 10 起,限制发生了变化,这使得它变得有点困难。

提前致谢

您可以尝试类似的方法:

  1. 保存当前应用状态
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. 在您的作品中获取当前状态
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)
        ....
    }
}