通过onResume() Fragment lifecycle方法调用多个实时数据库



我试图创建一个应用程序,其中涉及一个用户状态字段。有userStatus和customUserStatus。如果customUserStatus不为空,则userStatus将被设置为customUserStatus值,否则将被设置为"online"。这一切都发生在onResume()片段方法中。

我遇到的问题是onResume()的代码被多次调用…即使片段根本没有打开

可以看到,onResume代码被执行了多次,设置了不止一次的用户状态。

(Chat Fragment exit)
2021-02-10 11:59:34.828 22682-22682/com.user.myapp W/status: The chat fragment is no longer visible and the onStop has been called. Setting userStatus to offline
(ChatFragment opened)
2021-02-10 11:59:34.866 22682-22682/com.user.myapp W/status: setting the user status to custom user status... At the Gym
2021-02-10 11:59:34.868 22682-22682/com.user.myapp W/status: setting the user status to custom user status... At the Gym
(App exit - you can see that onResume() called multiple times...)
2021-02-10 11:59:46.201 22682-22682/com.user.myapp W/status: Setting user status to offline in the MainActivity
2021-02-10 11:59:46.260 22682-22682/com.user.myapp W/status: setting the user status to custom user status... At the Gym
2021-02-10 11:59:46.262 22682-22682/com.user.myapp W/status: setting the user status to custom user status... At the Gym
2021-02-10 11:59:46.263 22682-22682/com.user.myapp W/status: setting the user status to custom user status... At the Gym
我的onResume方法:
  1. 从数据库中获取用户对象
  2. 检查用户是否设置了自定义状态
  3. 如果没有,则将其状态设置为默认的->"online">
  4. 否则,将其状态设置为customStatus

我使用onResume作为检查当前片段是否已打开的一种方式,如果是,那么它将设置用户的状态。我希望它只执行一次。

@Override
public void onResume() {
super.onResume();
//Log.w("status", "The chat fragment is now visible and the onResume has been called. Setting userStatus to online");
String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users").child(userId);
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
User user = snapshot.getValue(User.class);
if(user.getCustomuserstatus() != null){
if(user.getUserstatus() != user.getCustomuserstatus()){
setUserStatus(user.getCustomuserstatus());
Log.w("status", "setting the user status to custom user status... " + user.getCustomuserstatus());
}
} else {
Toast.makeText(getActivity(), user.getCustomuserstatus(), Toast.LENGTH_SHORT).show();
setUserStatus("online");
Log.w("status", "setting the user status to online from the onresume");
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});

您无法控制Android调用onResume的频率。所以你的选项是:

  1. 跟踪你的代码在onResume中是否已经运行了一个更全局/静态的标志,并且只在它之前没有运行时执行它。
  2. 删除onPause中的侦听器,以便下次onResume运行时您再次附加第一个侦听器。

我更喜欢第二种方法,因为它导致代码更干净,并且不太可能让数据库侦听器逗留在用户不再查看的活动/片段上。

相关内容

最新更新