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

the*_*ire 2 java android firebase firebase-realtime-database

我有一个 Android 服务,它在onCreate以下位置调用它:

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());
        }
});
Run Code Online (Sandbox Code Playgroud)

我注意到,当我切换 wifi 和蜂窝数据时,我最终会看到“connected: false”消息,而没有“connected: 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());
        }
});
Run Code Online (Sandbox Code Playgroud)

现在,我成功读取打印了“connected: true”。

发生了什么?为什么我需要从 firebase 读取.info/connected才能触发?

Ale*_*amo 6

为什么我需要从 firebase 读取.info/connected才能触发?

答案保留在官方文档中

Firebase 实时数据库提供了一个特殊位置,/.info/connected每次 Firebase 实时数据库客户端的连接状态发生变化时都会更新该位置。

/.info/connected是一个布尔值,它在实时数据库客户端之间同步,因为该值取决于客户端的状态。换句话说,如果一个客户端读取/.info/connected为 false,则不能保证单独的客户端也会读取 false。

在 Android 上,Firebase 会自动管理连接状态以减少带宽和电池使用量。如果客户端没有活动侦听器、没有挂起的写入或 onDisconnect 操作,并且没有被该goOffline方法明确断开连接,Firebase 会在 60 秒不活动后关闭连接。

因此,在 Android 上,您还可以利用连接状态管理。因此,一旦您实施了上述解决方案,您将看到 SDK 以一种方式动态管理它,如果没有附加侦听器并且setValue()在过去 60 秒内在应用程序中没有使用任何写操作,连接会自动断开连接,但是a 的存在ValueEventListners将覆盖这一点,并确保与数据库的持续连接。您还可以查看这篇文章中的答案。

还有另一篇文章,我建议您阅读以更好地理解。