Detect if Firebase connection is lost/regained

前端 未结 6 885
[愿得一人]
[愿得一人] 2020-11-27 12:25

Is there a strategy that would work within the current Firebase offering to detect if the server connection is lost and/or regained?

I\'m considering some offline co

6条回答
  •  心在旅途
    2020-11-27 12:52

    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:

    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");
      }
    });
    

提交回复
热议问题