简体   繁体   中英

How to update status in remote database if the activity's onDestroy() method is not called?

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 (eg onTaskRemoved() in Service is not called in case an app is force-stopped). What could solve the problem?

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, eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM