如果 activity 的 onDestroy() 方法没有被调用,如何更新远程数据库中的状态?

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

目标是在 activity 被销毁后更新远程数据库中的状态。困难在于,如果系统终止进程,可以跳过 activity 的 onDestroy() 方法调用。 onStop() 和 onPause() 方法没有意义,因为它们不能确保 activity 完成。其他 activity 中的 ActivityResult 也不起作用,因为该应用程序可能会被终止。服务可能是解决方案,但恐怕它会与 activity 一起被杀死(例如,如果应用程序被强制停止,则不会调用服务中的 onTaskRemoved() )。什么可以解决问题?

到目前为止,我想出的最佳解决方案是将 Firebase Cloud Functions 与 Google Cloud Functions 结合使用。

长篇小说

由于要求是保证方法 运行 不早于 activity 的 onDestroy() 回调,一个有吸引力的解决方案是 Android Jetpack 的 WorkManager

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.

但是,让我们想象一下 phone 已经爆炸了。那么任务将是运行 NEVER。没关系,如果它不是要更改远程数据库状态,尤其是当状态在多个用户之间共享时。

因此,使用远程数据库最安全的方法是将远程功能安排为备份解决方案或将您的程序逻辑基于此。远程函数很可能会用您的程序以外的其他语言编写,但没有什么好害怕的,也完全值得去做。

这篇文章对我有帮助How to schedule a Cloud Function to run in the future with Cloud Tasks (to build a Firestore document TTL)。如果远程数据库是 Firebase(Firestore 或 Realtime),则可以编写 Cloud Functions,这将在数据库更改和调度 Google Cloud Tasks 时触发。后者可以 运行 HTTP 触发 Firebase Cloud Function 并做任何需要的事情,例如更新数据库值,或检查某些条件并重新安排 Google 云任务。所以,即使 phone 崩溃了,预定的任务也会被执行(同样,如果服务器不会发生故障......)。这些函数可以用 JavaScript 或 TypeScript 编写,非常容易掌握。