I use Firestore Beta in my app and I'd like to check if there is a working online connection to the Firestore Database. The documentation says that currently there is no direct way to query the connection state, but one can use the Firebase connection state as a workaround. The code snippet for that can also be found in this part of the documentation: Build presence in Cloud Firestore.
connectedRef = FirebaseDatabase.getInstance().getReference(".info/connected");
connectionStateListener = connectedRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
Boolean connected = snapshot.getValue(Boolean.class);
if (connected == null) {
changeState(FirebaseConnectionState.error);
return;
}
if (connected) {
changeState(FirebaseConnectionState.connected);
} else {
changeState(FirebaseConnectionState.not_connected);
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
L.i("FirebaseConnectionStateListener was cancelled");
}
});
The ValueEventListener itself is working and I get status updates. But for some reason the status switches from "connected" to "not connected" after 1 minute. Besides this being incorrect, I am not able to get it back to "connected" except restarting the app.
Here's some debug output:
2018-11-15 13:38:20.340: [FirebaseHeartbeatConnector] FirebaseHeartbeatConnector() called with: firebaseApp = [FirebaseApp{name=development, options=FirebaseOptions{applicationId=1:xxxxx:android:xxxxx, apiKey=xxxxx, databaseUrl=null, gcmSenderId=null, storageBucket=xxxx.appspot.com, projectId=xxxxx}}]
2018-11-15 13:38:20.480: [FirebaseHeartbeatConnector] startConnecting() called
2018-11-15 13:38:20.482: [FirebaseHeartbeatConnector] doSendFirestoreHeartbeatRequest() called
2018-11-15 13:38:20.840: [FirebaseHeartbeatConnector] change State called
2018-11-15 13:38:20.840: [FirebaseHeartbeatConnector] State changed initial -> not_connected
2018-11-15 13:38:21.380: [FirebaseHeartbeatConnector] change State called
2018-11-15 13:38:21.381: [FirebaseHeartbeatConnector] State changed not_connected -> connected
2018-11-15 13:39:20.514: [FirebaseHeartbeatConnector] change State called
2018-11-15 13:39:20.515: [FirebaseHeartbeatConnector] State changed connected -> not_connected
Why is that and how can I get a correct status update?
onDisconnectoperations, and is not explicitly disconnected by thegoOfflinemethod, Firebase closes the connection after 60 seconds of inactivity. Read more on the Detecting Connection State documentation.FirebaseDatabase.getInstance().keepSynced(true);makes a difference?keepSynced(true)created an empty listener, that's a neat little trick and saves having to create one manually. I just tested this and using justFirebaseDatabase.getInstance().getReference().keepSynced(true);does indeed stop it from disconnecting after 60 seconds.