gpt4 book ai didi

Firebase 数据库区分在线和离线数据

转载 作者:行者123 更新时间:2023-12-02 01:18:17 24 4
gpt4 key购买 nike

我知道 Firebase 实时数据库提供离线支持,但我如何区分在线连接提供的数据或本地离线更改提供的数据?

最佳答案

Firebase 数据库提供了一种特定的方法来了解客户端是否已连接。

谷歌写了一个方便的documentation在那个话题上。

从提供的链接:

Detecting Connection State

For many presence-related features, it is useful for a client to know when it is online or offline. Firebase Realtime Database clients provide a special location at /.info/connected which is updated every time the client's connection state changes.

DatabaseReference connectedRef = FirebaseDatabase.getInstance().getReference(".info/connected");
connectedRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
boolean connected = snapshot.getValue(Boolean.class);
if (connected) {
System.out.println("connected");
} else {
System.out.println("not connected");
}
}
@Override
public void onCancelled(DatabaseError error) {
System.err.println("Listener was cancelled");
}
});

/.info/connected is a boolean value which is not synchronized between clients because the value is dependent on the state of the client. In other words, if one client reads /.info/connected as false, this is no guarantee that a separate client will also read false.

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.



了解您的客户端是否连接到数据库将有助于区分在线和离线存储提供的数据。我很确定没有特定的方法可以查看 DataSnapshot来自在线或离线数据。

关于Firebase 数据库区分在线和离线数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41563120/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com