Ryan Pierce
Ryan Pierce

Reputation: 1633

Do Firebase Database listener's automatically detach and what causes it?

Using firebase, I added a listener to node "mReference" that may change value at any time. When my app is open or recently closed, the listener works. If the app has been closed for a long period of time (~days), the listener's onDataChange does not fire. Do Firebase Database listeners automatically detach after a certain period of time or because of a specific event?

ValueEventListener listener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

        Map map = dataSnapshot.getValue();
        // ...
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

        // ...
    }
};
mReference.addValueEventListener(listener);

Upvotes: 0

Views: 677

Answers (1)

Scott Kronheim
Scott Kronheim

Reputation: 772

You cannot rely on any Firebase listener inside an Android app to run constantly when the app is closed. Adding the listener to a Service will not work either because recent versions of Android will limit when Services can run (see documentation about Doze mode, and even more stringent restrictions added in Oreo).

If you need your app to take action when certain activity occurs in the database, one way to solve that is to use one or more Firebase realtime database triggers to identify the action in the database; within a trigger, you can use Firebase Cloud Messaging (FCM) to send a message to your device.

The database triggers run on the Firebase servers and do not require your app to be active. FCM can be configured to "wake up" your app so that it can take the appropriate action; FCM plays nicely with Doze mode and other recent restrictions on on app's background activity.

Upvotes: 2

Related Questions