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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With