Lalit Poptani
Lalit Poptani

Reputation: 67286

Firebase: keep listening to ChildEventListener though app exits

I am using Firebase for creating a small chat application. I want ChildEventListener to keep listening to the firebase database location though my app is in background or it is exited. Currently I am registering it and when my app exits or closed using finish(), after that none of my methods of ChildEventListener are getting called like onChildAdded or onChildChanged though I haven't called removeEventListener.I want ChildEventListener to be always running in background. Is there anyway of doing that?

Upvotes: 10

Views: 4691

Answers (2)

Garry
Garry

Reputation: 2355

Try firebase cloud messaging with firebase functions.

Upvotes: 0

Raghavendra B
Raghavendra B

Reputation: 441

Use service to listen your ChildEventListener

    public class ChildEventListener extends Service {
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            //Adding a childevent listener to firebase                
            Firebase myFirebaseRef = new Firebase("FirebaseURL");
            myFirebaseRef.child("FIREBASE_LOCATION").addValueEventListener(new ValueEventListener() {

                @Override
                public void onDataChange(DataSnapshot snapshot) {
                    //Do something using DataSnapshot say call Notification
                }

                @Override
                public void onCancelled(FirebaseError error) {
                    Log.e("The read failed: ", error.getMessage());
                }
            });

          }

                @Override
                public void onCancelled(FirebaseError firebaseError) {
                    Log.e("The read failed: ", firebaseError.getMessage());
                }
            });

            return START_STICKY;
       }

  }

register your Service inside Manifest

    <service android:name=".ChildEventListener "/>

Start your Service and listen for childEvents, where/when to start your service is up to your chat app design

Upvotes: 10

Related Questions