如果用户关闭wi-fi、3g、4g等和反向(无互联网连接)。Firebase数据库指定子连接:(真/假)因此,当互联网连接、wi-fi、3g、4g等关闭或丢失时,用户处于离线状态,因此无法找到他。
记住两个场景:之前和之后。如果用户在其他用户搜索他之前离线,则他不会显示在列表结果中;如果用户在其他用户搜索他之后离线,则在该用户上将不再显示可用图标
有人能帮我解决这个问题吗?
发布于 2018-05-23 14:27:05
为了解决这个问题,您可以在Firebase实时数据库中创建一个新节点来保存所有在线用户,因此当用户打开应用程序时,您将立即将他的id添加到这个新创建的节点中。然后,如果你想检查用户是否在线,只需检查他的id是否存在于列表中。
您还可以为数据库中的每个用户添加一个名为isOnline
的新属性,然后相应地更新它。
为此,我建议您使用Firebase的内置onDisconnect()
方法。它使您能够预定义在客户端断开连接时立即发生的操作。
您还可以检测用户的连接状态。对于许多与在线状态相关的功能,让你的应用程序知道它是在线还是离线是很有用的。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");
}
});
发布于 2019-07-01 04:04:35
虽然这晚了一年多,但为了澄清混乱。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) {
}
});
https://stackoverflow.com/questions/50480943
复制相似问题