我浏览了所有文档和许多博客,但没有得到答案。
事情是我有 100 个到 firebase 实时数据库的同时连接的初始免费配额。这意味着我的用户中有 100 个可以使用我的应用程序。在使用应用程序之后,除非并且直到用户不 销毁
应用程序 connection
仍然对该用户保持打开状态,因此在此期间其他用户无法访问。
所以我的问题是,如果我从数据库引用中删除监听器,这是否也会关闭连接
?
ValueEventListener listener = null;
DatabaseRefference ref =FirebaseDatabase.getInstance().getRefference("user");
listener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
ref.removeEventListener(listener);
//----Doing Stuffs
}
}
ref.addListenerForSingleValueEvent(listener);
我想要实现的是,当 User1 获得他的搜索结果时,他/她将不再保持连接
,这样另一个用户就可以进入数据库。
最佳答案
Firebase 自动管理连接。这在 Realtime Database Guide 中有解释。 :
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.
另请注意,当使用 addListenerForSingleValueEvent()
添加监听器时,它会在 onDataChange()
运行后自动删除。您不需要调用 removeEventListenter()
,就像您在发布的代码中所做的那样。这在 documentation 中有描述。 :
Read data once
In some cases you may want a callback to be called once and then immediately removed, such as when initializing a UI element that you don't expect to change. You can use the addListenerForSingleValueEvent() method to simplify this scenario: it triggers once and then does not trigger again.
您可以 detect connection state在伪位置 /.info/connected
处随监听器更改。请注意,这确实算作一个正常的“Activity ”监听器,不会抑制自动断开处理。
获得连接状态管理可见性的另一种方法是使用 FirebaseDatabase.getInstance().setLogLevel(Logger.Level.DEBUG) 启用调试日志记录.
关于android - "removeEventListener"(android) 是否关闭 Firebase 实时数据库连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46002337/