检测 Firebase 连接是否丢失/恢复
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11351689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Detect if Firebase connection is lost/regained
提问by Kato
Is there a strategy that would work within the current Firebase offering to detect if the server connection is lost and/or regained?
是否有适用于当前 Firebase 产品的策略来检测服务器连接是否丢失和/或重新获得?
I'm considering some offline contingencies for mobile devices and I would like a reliable means to determine when the Firebase data layer is available.
我正在考虑移动设备的一些离线突发事件,我想要一种可靠的方法来确定 Firebase 数据层何时可用。
回答by Michael Lehenbauer
This is a commonly requested feature, and we just released an API update to let you do this!
这是一个普遍要求的功能,我们刚刚发布了一个 API 更新来让您做到这一点!
var firebaseRef = new Firebase('http://INSTANCE.firebaseio.com');
firebaseRef.child('.info/connected').on('value', function(connectedSnap) {
if (connectedSnap.val() === true) {
/* we're connected! */
} else {
/* we're disconnected! */
}
});
Full docs are available at https://firebase.google.com/docs/database/web/offline-capabilities.
完整文档可在https://firebase.google.com/docs/database/web/offline-capabilities 获得。
回答by Baris
Updated: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. Here is an example:
更新:对于许多与在线状态相关的功能,客户端知道它何时在线或离线非常有用。Firebase 实时数据库客户端在 /.info/connected 提供一个特殊位置,每次客户端的连接状态更改时都会更新该位置。下面是一个例子:
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");
}
});
回答by knod
I guess this changed in the last couple of months. Currently the instructions are here: https://firebase.google.com/docs/database/web/offline-capabilities
我想这在过去几个月发生了变化。目前的说明在这里:https: //firebase.google.com/docs/database/web/offline-capabilities
In summation:
总之:
var presenceRef = firebase.database().ref("disconnectmessage");
// Write a string when this client loses connection
presenceRef.onDisconnect().set("I disconnected!");
and:
和:
var connectedRef = firebase.database().ref(".info/connected");
connectedRef.on("value", function(snap) {
if (snap.val() === true) {
alert("connected");
} else {
alert("not connected");
}
});
I'll admit I don't know a lot about how references are set, or what that means (are you making them out of thin air or do you have to have already created them beforehand?) or which one of those would trigger something on the server as opposed to something on the front end, but if the link is still current when you read this, a little more reading might help.
我承认我不太了解引用是如何设置的,或者这意味着什么(你是凭空制作它们还是你必须事先创建它们?)或者其中哪一个会触发某些事情在服务器上,而不是在前端,但是如果您阅读本文时链接仍然是最新的,多读一点可能会有所帮助。
回答by Kishan Solanki
For android you can make user offline by just a single function called onDisconnect()
对于android,您可以通过一个名为的函数使用户离线 onDisconnect()
I did this in one of my chat app where user needs to get offline automatically if network connection lostor user disconnected from Internet
我在我的一个聊天应用程序中做到了这一点,如果网络连接丢失或用户与互联网断开连接,用户需要自动离线
DatabaseReference presenceRef = FirebaseDatabase.getInstance().getReference("USERS/24/online_status");
presenceRef.onDisconnect().setValue(0);
On disconnecting from network Here I am making online_status0 of user whose Id is 24 in firebase.
与网络断开连接时,我online_status在 firebase 中创建了0 个 ID 为 24 的用户。
getReference("USERS/24/online_status")is the path to the value you need to update on offline/online.
getReference("USERS/24/online_status")是您需要在离线/在线更新的值的路径。
You can read about it in offline capabilities
您可以在离线功能中阅读它
Note that firebase takes time around 2-10 minutes to execute onDisconnect() function.
请注意,firebase 执行 onDisconnect() 函数需要大约 2-10 分钟的时间。
回答by Piotr Jankiewicz
The suggested solution didn't work for me, so I decided to check the connection by writing and reading 'health/check' value. This is the code:
建议的解决方案对我不起作用,所以我决定通过写入和读取“健康/检查”值来检查连接。这是代码:
const config = {databaseURL: `https://${projectName.trim()}.firebaseio.com/`};
//if app was already initialised delete it
if (firebase.apps.length) {
await firebase.app().delete();
}
// initialise app
let cloud = firebase.initializeApp(config).database();
// checking connection with the app/database
let connectionRef = cloud.ref('health');
connectionRef.set('check')
.then(() => {
return connectionRef.once("value");
})
.then(async (snap) => {
if (snap.val() === 'check') {
// clear the check input
await connectionRef.remove();
// do smth here becasue it works
}
});


