【发布时间】:2021-03-07 18:59:48
【问题描述】:
在应用程序启动时,ChildEventListener 会触发 firebase 数据库中存在的子数量。例如,如果我的数据库中已经有 3 个孩子,那么当我启动我的应用程序时,侦听器将被调用 3 次。 s 我已经在我的服务类中定义了监听器的代码,并且我正在从我的 Splash 类启动服务。
来自 SplashScreen.class
startService(new Intent(this , BackgroundService.class));
来自 BackgroundService.class
listenToJob()方法,在Service的onStartCommand()方法中
private void listenToJob (){
String collectionName = "rideRequest";
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference(collectionName);
ChildEventListener childEventListener = new ChildEventListener() {
@Override
public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
Toast.makeText(BackgroundService.this, "Hey, new child is added.", Toast.LENGTH_SHORT).show();
OnChildCreated(snapshot);
}
@Override
public void onChildChanged(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
}
@Override
public void onChildRemoved(@NonNull DataSnapshot snapshot) {
}
@Override
public void onChildMoved(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
};
myRef.addChildEventListener(childEventListener);
}
我不知道是什么导致了这种行为。 onChildAdded() 方法不应该只在将新子添加到数据库时调用吗?我的数据库中已经有 3 个孩子,当我打开我的应用程序时,这个 onChildAdded() 方法被调用了 3 次。
我希望这个方法只有在将孩子添加到数据库时才会启动!
【问题讨论】:
标签: android firebase firebase-realtime-database