问题
As explained in some answers:
On Android, Firebase automatically manages connection state to reduce bandwidth and battery usage. When a client has no active listeners, no pending write or onDisconnect operations, and is not explicitly disconnected by the goOffline method, Firebase closes the connection after 60 seconds of inactivity.
The problem is that after 60s, even after I go to an activity with a complete new reference, event listener, etc.. It still says it is disconnect, when in fact, it is not.
val connectedRef = FirebaseDatabase.getInstance().getReference(".info/connected")
var connectListener : ValueEventListener? = null
fun checkConnection() {
connectListener = connectedRef.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
val connected = snapshot.getValue(Boolean::class.java)!!
if (connected) {
Log.d("FRAG", "CONNECTED")
else{
Log.d("FRAG", "DISCONNECTED")
}
}
override
fun onCancelled(error: DatabaseError) {
System.err.println("Listener was cancelled")
}
})
}
override fun onDetach() {
super.onDetach()
if (connectListener != null){
connectedRef.removeEventListener(connectListener)
}
}
How can I make sure I maintain or create a new connection to Firebase? I call the checkConnection
method every onAttach
of a fragment and onStart
of an activity.
回答1:
If you have an active listener on any data that is read from the server, the connection should remain open unless you've explicitly called goOffline()
in your code. Note that .info/connected
itself does not require reading from the server, so does not keep the connection open.
It seems you're using the realtime database to build an presence system on an otherwise Firestore based app. In that case: Cloud Firestore uses a gRPC-based protocol to talk between client and server, while the Firebase Realtime Database uses web sockets. They're in no way compatible or even comparable. Keeping an active listener on data in Firestore does not keep a connection to RTDB open. That's why the example in the Firestore documentation also writes an actual data node to the realtime database.
来源:https://stackoverflow.com/questions/49114436/firebase-connection-detection-does-not-work-after-60-seconds