0

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.

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
Raid Eye
  • 23
  • 5
  • `user active or not` I think that also conclude the part if User press Home button and your app is no longer visible on screen . I think you better you do it in `onStop` of Application and also mark user in active. https://stackoverflow.com/questions/57194442/detect-application-is-paused-on-click-on-home – ADM Mar 22 '22 at 05:32
  • onStop is not a solution because what if Internet went off? The solution is to use a handler which run after every X(5) seconds and update current time. From other end check if last update time was greater than X+2(7) seconds then the user is offline. – Faizan Haidar Khan Mar 22 '22 at 09:32

1 Answers1

0

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");
           
        }

         ....
}
ashwath hegde
  • 606
  • 8
  • 12