问题
I am using the presence system in Firebase to show "Online", if my client is connected to the network and "Offline", if the connection gets lost somehow.
This is very important for my client as it indicates, if the user can send a message now.
It works well sometimes and sometimes not and there lies the problem.
This is what I am doing,
mConnectionRef = FirebaseDatabase.getInstance().getReference(".info/connected");
mConnectionRef.addValueEventListener(mPresenceListener);
and this,
private ValueEventListener mPresenceListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
boolean connected = snapshot.getValue(Boolean.class);
Timber.d("Connected: %s", connected);
Presence.getInstance().setIsOnline(connected);
if (connected) {
if (mPresenceStatus != null) {
mPresenceStatus.setText(ResourceUtils.getString(R.string.label_online));
Drawable image = ResourceUtils.getDrawable(R.drawable.ic_presence_online);
mPresenceStatus.setCompoundDrawablesWithIntrinsicBounds(image, null, null, null);
}
} else {
mPresenceStatus.setText(ResourceUtils.getString(R.string.label_offline));
Drawable image = ResourceUtils.getDrawable(R.drawable.ic_presence_offline);
mPresenceStatus.setCompoundDrawablesWithIntrinsicBounds(image, null, null, null);
}
}
@Override
public void onCancelled(DatabaseError error) {
Presence.getInstance().setIsOnline(false);
mPresenceStatus.setText(ResourceUtils.getString(R.string.label_offline));
Drawable image = ResourceUtils.getDrawable(R.drawable.ic_presence_offline);
mPresenceStatus.setCompoundDrawablesWithIntrinsicBounds(image, null, null, null);
}
};
Sometimes, after the client is idle for a long period of time and then I open the app, I can see that it prints "Connected: true" and then immediately prints "Connected: false" and this repeats every 2-3 seconds even if the client has a working network connection.
Now the solution to this problem is to log out using mFirebaseUser.logout() and log in again and then the listener works perfectly.
Now if I don't use the app again for a few hours this problem occurs again and the listener starts behaving abnormally.
What am I doing wrong here? What the problem actually is? How can this weird problem be solved?
Any help will be highly appreciated.
来源:https://stackoverflow.com/questions/40233039/firebase-info-connected-showing-wrong-connection-states