我想在应用程序终止时更新 Firebase 中的数据。我怎样才能做到这一点
我使用了
onDestroy
和onPause
,但它们没有实现我想要的功能。当我使用 OnPause 时,每次应用程序进入后台时,它都会执行更新操作,我也不希望这样。
// This onDestroy didn't work OnPause, every time the application goes to the background
override fun onDestroy() {
super.onDestroy()
Log.d("ClosingService", "Service is destroyed. Updating user data...")
Update_User_Data(dataManager.userDataList)
}
fun Update_User_Data(newDataList : ArrayList<User_Structure>){
val tasks = newDataList.map { i ->
val userRef = db.collection("users").document(i.userId)
userRef.update(mapOf(
"username" to i.username,
"favorites" to i.favorites,
"parts" to i.parts,
"points" to i.points
))
}
Tasks.whenAllComplete(tasks).addOnCompleteListener {
if (it.isSuccessful) {
println("All user data updated successfully!")
} else {
println("Error updating some user data.")
}
}
}
我使用了OnDestroy和OnPouse,但它们没有实现我想要的功能。
onDestroy
并不总是被称为。所以你不能依赖它。正如 @MarsAtomic 在他的评论中已经提到的,您应该考虑使用 onSaveInstanceState() 来代替:
调用以在活动被终止之前检索每个实例的状态,以便可以在
或onCreate(Bundle)
中恢复状态。onRestoreInstanceState(Bundle)