gpt4 book ai didi

java - Firebase 实时数据库 .info/connected False 当它应该是 True

转载 作者:行者123 更新时间:2023-11-29 16:34:11 30 4
gpt4 key购买 nike

我有一个在 onCreate 调用它的 Android 服务:

FirebaseDatabase database = FirebaseDatabase.getInstance();
database.getReference(".info/connected").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
Log.d(TAG, "connected: " + snapshot.getValue(Boolean.class));
}

@Override
public void onCancelled(@NonNull DatabaseError error) {
Log.w(TAG, "Failed to read value.", error.toException());
}
});

我注意到,当我进行一些切换 wifi 和蜂窝数据时,我最终会看到一条“已连接:false”消息,而没有看到“已连接:true”消息。除了 Firebase 实时数据库,我还在服务中运行 Firestore,此时 Firestore 已正确连接。

然后我触发 Android 服务运行这段代码:

FirebaseDatabase.getInstance().getReference("random/data").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
boolean connected = snapshot.getValue(Boolean.class);
Log.d(TAG, "random data: " + connected);
}

@Override
public void onCancelled(@NonNull DatabaseError error) {
// Failed to read value
Log.w(TAG, "cancelled system/online.", error.toException());
}
});

现在,我得到了一个成功的读取并且打印了“connected: true”。

这是怎么回事?为什么我需要从 firebase 读取 .info/connected 来触发?

最佳答案

Why do I need to read from firebase for .info/connected to trigger?

答案在 offical documentation 中:

Firebase Realtime Database provides a special location at /.info/connected which is updated every time the Firebase Realtime Database client's connection state changes.

/.info/connected is a boolean value which is not synchronized between realtime database 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.

因此在 Android 上,您还可以利用连接状态管理。因此,一旦您实现了上述解决方案,您将看到 SDK 以一种动态方式管理此问题,如果没有附加监听器并且没有使用 setValue() 进行写入操作,则连接会自动断开连接在最后 60 秒内在应用程序中,但是 ValueEventListners 的存在将覆盖它并确保与数据库的持续连接。您还可以查看此 post 中的答案.

还有一个post我建议您阅读以更好地理解。

关于java - Firebase 实时数据库 .info/connected False 当它应该是 True,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53069484/

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