Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if Firebase connection is lost/regained

Tags:

firebase

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 contingencies for mobile devices and I would like a reliable means to determine when the Firebase data layer is available.

like image 668
Kato Avatar asked Jul 05 '12 19:07

Kato


People also ask

How can I tell if Firebase is connected Android?

If you want to know if the client is connected to the server before calling setValue() , you can attach a listener to . info/connected .

Does Firebase storage work offline?

Firebase has great option of using their database and sending data to their db even if you are offline, and then when the connection is up again, it sends automatically the data to the db.


2 Answers

This is a commonly requested feature, and we just released an API update to let you do this!

var firebaseRef = new Firebase('http://INSTANCE.firebaseio.com'); firebaseRef.child('.info/connected').on('value', function(connectedSnap) {   if (connectedSnap.val() === true) {     /* we're connected! */   } else {     /* we're disconnected! */   } }); 

Full docs are available at https://firebase.google.com/docs/database/web/offline-capabilities.

like image 56
Michael Lehenbauer Avatar answered Sep 22 '22 23:09

Michael Lehenbauer


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");   } }); 
like image 43
Baris Avatar answered Sep 21 '22 23:09

Baris