Home > Net >  Check if app's in foreground or background
Check if app's in foreground or background

Time:07-17

I want to update user status in firestore to online and offline according to whether the app runs in the background or foreground. I'm using LifecycleObserver for it, but the problem is I have to call it in every single activity for it to work.

Is there a way to do this without having to call it in every activity?

Observer class:

class Observer(private val currentUser: User): LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onEnteredForeground() {
        if (!currentUser.isOnline)
            updateStatus(true)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun onEnteredBackground() {
        if (currentUser.isOnline) {
            updateStatus(false)
        }
    }

    private fun updateStatus(status: Boolean) {
        val db = FirebaseFirestore.getInstance()
        db.collection("users").document(currentUser!!.uid)
            .update(
                "isOnline", status
            )
            .addOnSuccessListener {
                Log.d(ContentValues.TAG, "DocumentSnapshot successfully written!")
                return@addOnSuccessListener
            }
            .addOnFailureListener { e ->
                Log.w(ContentValues.TAG, "Error writing document", e)
                return@addOnFailureListener
            }
    }
}

How I call it:

lifecycle.addObserver(Observer(user))

CodePudding user response:

Try this

your build.gradle file:

dependencies {
    implementation "android.arch.lifecycle:extensions:1.1.0"
}

Then in your Application class,add :

class ArchLifecycleApp : Application(), LifecycleObserver {

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

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun onAppBackgrounded() {
        Log.d("MyApp", "App in background")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onAppForegrounded() {
        Log.d("MyApp", "App in foreground")
    }
}

update your AndroidManifest.xml file :

<application
    android:name=".ArchLifecycleApp"
    //Your extra code
    ....>
</application>
  • Related