Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 855
Lalit Poptani Avatar asked Jul 16 '16 12:07

Lalit Poptani


1 Answers

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

like image 117
Raghavendra B Avatar answered Sep 27 '22 23:09

Raghavendra B