Issue
The goal is to update status in a remote database once the activity gets destroyed. The difficulty is that the activity's onDestroy() method call can be skipped if system kills the process. The methods onStop() and onPause() are of no interest, since they don't ensure the activity finalization. ActivityResult in other activity would not work either, because the app could be killed. Service might be the solution, but I'm afraid it gets killed along with the activity (e.g. onTaskRemoved() in Service is not called in case an app is force-stopped). What could solve the problem?
Solution
The best solution I have come up with so far is the use of Firebase Cloud Functions together with Google Cloud Functions.
The short story long
Since the requirement is to guarantee a method run no earlier than the activity's onDestroy()
callback, an attractive solution is Android Jetpack's WorkManager for
WorkManager is an API that makes it easy to schedule reliable, asynchronous tasks that are expected to run even if the app exits or the device restarts.
However, lets imagine that the phone have blown up. Then the task will be run NEVER. Which is ok, if it is not meant to change the remote database state especially when the state is shared between multiple users.
Therefore, the safest way to work with remote databases is to schedule remote functions as a backup solution or base your program logic on that. The remote functions most probably would be written in other language than your program, but there is nothing to be scared of and totaly worth to do.
This article helped me How to schedule a Cloud Function to run in the future with Cloud Tasks (to build a Firestore document TTL). In case the remote database is Firebase (Firestore or Realtime), it is possible to write Cloud Functions, which would be triggered on database changes and schedule Google Cloud Tasks. The latter can run HTTP triggered Firebase Cloud Function and do whatever is needed, e.g. update the database values, or check for some condition and reschedule the Google Cloud Task. So, even if a phone blows up, the scheduled task will be executed (again, if servers would not malfunction..). The functions can be written in JavaScript or TypeScript, wich is pretty easy to grasp.
Answered By - Michael Zur