0

Is there a possibility to execute code when your activity is closed? And how do I close Realtime Database connections?

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Adrian8115
  • 17
  • 4

1 Answers1

0

How do I close Realtime Database connections?

When you're referring to closing a connection to a Realtime Database, yes, FirebaseDatabase#goOffline():

Shuts down our connection to the Firebase Database backend until goOnline is called.

But I think that you're not looking to go offline, as all it does, is affects the way that database queries work. So if you're using this approach, then you have to manage the connection state yourself using goOffline/goOnline. Besides that, according to the official documentation regarding detecting connection state:

On Android, Firebase automatically manages the connection state to reduce bandwidth and battery usage. When a client has no active listeners, no pending write or onDisconnect operations, and is not explicitly disconnected by the goOffline method, Firebase closes the connection after 60 seconds of inactivity.

So there is no need to do that yourself since Firebase automatically does that for you.

What I think you're looking for is to read the data and detach a listener right after that. That can be achieved using Query#addListenerForSingleValueEvent(@NonNull ValueEventListener listener) which detaches the listener after the values from the databases are obtained and thus does not persist as an active listener. If you fetch all the data using this method, the connection will be closed after about a minute of inactivity. If you want to monitor the connection state yourself, then you can use a listener at .info/connected as explained in the official documentation regarding detecting connection state.

Please also note that the same thing can be achieved using Query#get().

If you need a persistent listener, then you should detach the listener accordingly to the life cycle of your activity. Also note, that @HarkishanPansuriya solution is not quite correct, because onDestroy is not always called.

Is there a possibility to execute code when your activity is closed?

Yes, you can, using a service. You can use a background service that can process data in the background.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193