Android - Firestore/firebase Realtime Database ".info/connected" Returns Wrong Connection State
Solution 1:
This might be caused by Firebase closing the connection due to inactivity, which only happens on Android. From the Detecting Connection State documentation:
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 thegoOffline
method, Firebase closes the connection after 60 seconds of inactivity.
Because your app isn't making real use of the Realtime Database (you're using Cloud Firestore instead), there won't be any other write operations or other listeners attached, so the connection is closed automatically. You'll likely see something like the below in logcat:
V/FA: Inactivity, disconnecting from the service
As a possible workaround, you could try attaching a listener to any node in the Realtime Database to keep the connection alive (anything will do, even if it doesn't actually exist):
FirebaseDatabase.getInstance().getReference("keepalive").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
// Do nothing - this listener just keeps the connection alive
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Log.i("Keepalive listener was cancelled");
}
});
Alternatively, as suggested by Frank van Puffelen, you can trick Firebase into hanging onto the connection by telling it to keep the entire Realtime Database synced, using keepSynced()
on an empty reference:
FirebaseDatabase.getInstance().getReference().keepSynced(true);
You'll need to remember to remove the keepalive listener or undo keepSynced()
when you actually want to mark the user's presence as disconnected, though.
Finally, with both of these examples, you still need to attach and make use of the .info/connected
connection state listener to handle changes in connection state:
For many presence-related features, it is useful for your app to know when it is online or offline. Firebase Realtime Database provides a special location at
/.info/connected
which is updated every time the Firebase Realtime Database client's connection state changes. Here is an example:
DatabaseReference connectedRef = FirebaseDatabase.getInstance().getReference(".info/connected"); connectedRef.addValueEventListener(newValueEventListener() { @OverridepublicvoidonDataChange(DataSnapshot snapshot) { boolean connected = snapshot.getValue(Boolean.class); if (connected) { System.out.println("connected"); } else { System.out.println("not connected"); } } @OverridepublicvoidonCancelled(DatabaseError error) { System.err.println("Listener was cancelled"); } });
Post a Comment for "Android - Firestore/firebase Realtime Database ".info/connected" Returns Wrong Connection State"