从JobIntentService使用Firestore:无法获得对Firestore客户端的脱机持久性的独占锁定

时间:2018-02-25 13:08:42

标签: firebase kotlin background-process google-cloud-firestore jobintentservice

每当我在设置闹钟时退出应用程序并且当应用程序为“DEAD”时闹钟响起,我在尝试更新Firestore中的字段时会出现异常。

当应用程序在前台运行时代码有效,所以我真的不知道发生了什么。无论哪种方式,这里是从JobIntentService调用的2个函数的代码,而JobIntentService又是从BroadcastReceiver创建的:

private val firestoreInstance: FirebaseFirestore by lazy { FirebaseFirestore.getInstance() }

    fun updateTaskCompletedSessions(taskDocRefPath: String, completedSessions: Int){
        val taskDocRef = firestoreInstance.document(taskDocRefPath)
        taskDocRef.get().addOnSuccessListener { documentSnapshot ->
            documentSnapshot.reference
                    .update(mapOf("completedSessions" to completedSessions))
        }
    }

    fun updateTaskSessionProgress(taskDocRefPath: String, sessionProgress: String){
        val taskDocRef = firestoreInstance.document(taskDocRefPath)
        taskDocRef.get().addOnSuccessListener { documentSnapshot ->
            documentSnapshot.reference
                    .update(mapOf("sessionProgress" to sessionProgress))
        }
    }

完整错误如下:

  

无法获得对Firestore客户端脱机持久性的独占锁定。

     

这通常意味着您在应用中使用来自多个进程的Firestore。请注意,多进程Android应用程序会在所有进程中执行Application类中的代码,因此您可能需要避免在Application类中初始化Firestore。如果您故意在多个进程中使用Firestore,则只能在其中一个进程中启用脱机持久性(即调用setPersistenceEnabled(true))。

我将不胜感激任何帮助。谢谢!

1 个答案:

答案 0 :(得分:0)

我很高兴地宣布我找到了解决方案!我正在使用两个因此触发JobIntentServices - 一个用于completedSessions,另一个用于sessionProgress。 (糟糕的设计,我知道......)

当我玩它并且只使用一个JobIntentService来调用这两个函数时,异常就消失了,这很有意义。