[英]Firebase connection check online offline status in Android
如果用户同时关闭 wi-fi、3g、4g 等并反向(没有互联网连接)。 Firebase 数据库名称子连接:(true/false) 因此,当互联网连接、wi-fi、3g、4g 等关闭或丢失时,用户处于离线状态,因此无法找到他。
记住两个场景:之前和之后。 如果用户在其他用户搜索他之前离线,那么他不会显示在列表结果中,如果用户在其他用户搜索他之后离线,那么它会在用户上显示 NO MORE AVAILABLE 图标
请有人帮助我解决这个问题。
为了解决这个问题,您可以在 Firebase 实时数据库中创建一个新节点来保存所有在线用户,这样当用户打开应用程序时,您将立即将他的 id 添加到这个新创建的节点中。 然后,如果要检查用户是否在线,只需检查列表中是否存在他的id。
您还可以为数据库中的每个用户添加一个名为isOnline
的新属性,然后相应地更新它。
为此,我建议您使用 Firebase 的内置onDisconnect()
方法。 它使您能够预定义在客户端断开连接时将立即发生的操作。
请参阅Firebase 文档。
您还可以检测用户的连接状态。 对于许多与在线状态相关的功能,了解您的应用何时在线或离线非常有用。 Firebase 实时数据库在/.info/connected
提供了一个特殊位置,每次 Firebase 实时数据库客户端的连接状态更改时都会更新该位置。 以下是官方文档中的一个示例:
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");
}
});
虽然这已经晚了一年多,但还是要澄清一下混乱。 Alex 的问题想要实现一个实时聊天场景,在该场景中,每个用户都可以在自己的终端或设备上查看每个人的在线状态。 一个简单的解决方案是创建一个节点,所有用户都会在其中注入他们的在线状态。 例如
//say your realtime database has the child `online_statuses`
DatabaseReference online_status_all_users = FirebaseDatabase.getInstance().getReference().child("online_statuses");
//on each user's device when connected they should indicate e.g. `linker` should tell everyone he's snooping around
online_status_all_users.child("@linker").setValue("online");
//also when he's not doing any snooping or if snooping goes bad he should also tell
online_status_all_users.child("@linker").onDisconnect().setValue("offline")
因此,如果另一个用户,比如mario
从他的一端检查linker
,他可以确定如果linker
在线,一些窥探仍在进行中,即
DatabaseReference online_status_all_users = FirebaseDatabase.getInstance().getReference().child("online_statuses");
online_status_all_users.child("@linker").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String snooping_status = dataSnapshot.getValue(String.class);
//mario should decide what to do with linker's snooping status here e.g.
if(snooping_status.contentEquals("online")){
//tell linker to stop doing sh*t
}else{
//tell linker to do a lot of sh****t
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.