Using Firestore from a JobIntentService: Failed to

2019-08-19 00:03发布

Whenever I exit the app while I have an alarm set and the alarm goes off while the app is "DEAD" I get an Exception while trying to update a field in Firestore.

The code works when the app is running in the foreground so I really have no clue of what is going on. Either way, here is the code for 2 functions which get called from the JobIntentService which is in turn created from a 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))
        }
    }

The full error goes as follows:

Failed to gain exclusive lock to the Firestore client's offline persistence.

This generally means you are using Firestore from multiple processes in your app. Keep in mind that multi-process Android apps execute the code in your Application class in all processes, so you may need to avoid initializing Firestore in your Application class. If you are intentionally using Firestore from multiple processes, you can only enable offline persistence (i.e. call setPersistenceEnabled(true)) in one of them.

I will appreciate any help. Thank you!

1条回答
虎瘦雄心在
2楼-- · 2019-08-19 00:44

I'm happy to announce that I found a solution! I was using two consequently firing JobIntentServices - one for completedSessions, the other for sessionProgress. (Bad design, I know...)

When I played around with it and made just ONE JobIntentService to call both of these functions, the exception is gone which makes perfect sense.

查看更多
登录 后发表回答