> For the complete documentation index, see [llms.txt](https://sagar-r-kothari.gitbook.io/blog/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://sagar-r-kothari.gitbook.io/blog/_posts/2020-07-11-anroid-background-foreground-check.md).

# 2020-07-11-Anroid-Background-Foreground-Check

## build.gradle (Module: app)

```ruby
dependencies {
    ...
    implementation 'androidx.lifecycle:lifecycle-process:2.2.0'
    ...
}
```

## MainActivity.kt

```kotlin
class MainActivity : AppCompatActivity(), LifecycleObserver {
    private var isAppInForeground = false
    override fun onCreate() {
        super.onCreate()
        ProcessLifecycleOwner.get().lifecycle.addObserver(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        ProcessLifecycleOwner.get().lifecycle.removeObserver(this)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onForegroundStart() {
        isAppInForeground = true
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun onForegroundStop() {
        isAppInForeground = false
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    // I need to check if app is on foreground or background
    fun someRandomFunction() {
        if (isAppInForeground) {
            println("execute foreground code")
        } else {
            println("execute background code")
        }
    }
}
```
