'How to update a field when my app is killed(Firebase)

I have an apps where I need to track my user active or not . So I create a service class to update user active status.Here is my service class code

class ServiceClass : Service() {
override fun onBind(p0: Intent?): IBinder? {
    return null
}

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
   Repository.updateActiveStatus(true)
    return START_NOT_STICKY
}

override fun onDestroy() {
    super.onDestroy()
  Repository.updateActiveStatus(false)
}

override fun onTaskRemoved(rootIntent: Intent?) {
    super.onTaskRemoved(rootIntent)
    Log.d("TAGService", "onTaskRemoved: false")
    Firebase.firestore.collection("User").document(Firebase.auth.uid.toString())
        .update("active", true).addOnSuccessListener {
            Log.d("TAGService", "onTaskRemoved: updated")
        }
    stopSelf()
}}

here is my manifest code

<service android:name=".utils.ServiceClass" android:stopWithTask="false"></service>

But when I open my apps its update its active status but when I destroy or killed my code its not updating.



Solution 1:[1]

If you want to check user is active or not then it better to check at application level instead of service level. And if you like to update the UI you can try Event bus. Here is the sample code.

        public class AppOpenManager :Application.ActivityLifecycleCallbacks, LifecycleObserver{
      .....
      @OnLifecycleEvent(ON_START)
        public fun onStart() {
            Log.d(LOG_TAG, "onStart");
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        public fun onAppBackgrounded() {
            Log.d(LOG_TAG,"APP BACKGROUNDED");
           
        }

         ....
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ashwath hegde