Firebase .info/connected showing wrong connection states

时间秒杀一切 提交于 2019-12-10 11:16:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!