Firebase: keep listening to ChildEventListener though application exits

I use Firebase to create a small chat application. I want the ChildEventListener to continue listening to the location of the firebase database, although my application is in the background or it is terminated. I am currently registering it, and when my application exits or closes with finish() , after that none of my ChildEventListener methods are called as onChildAdded or onChildChanged , although I did not call removeEventListener . I want the ChildEventListener to always run in the background. Is there any way to do this?

+8
source share
3 answers

Use the service to listen on 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 the manifest

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

Launch your Service and listen to childEvents, where / when to start your work depends on the design of your chat.

+9
source

You can try to use a global variable by extending the Application class, and so you will reference your ChildEventListner, and if you have multiple Listners, you can always use a map or something like this, and when you exit your application, if the list that you are looking for in a null value, set it again or uninstall and install a new Listner (to avoid multiple lists for the same database link).

here is an example:

 public class MApplication extends Application { private static Map<String,ChildEventListener> mapListners = new HashMap<>(); public static ChildEventListener getChildEventListener(String key) { if (mapListners.containsKey(key)) return mapListners.get(key); else return null; } public static void setChildEventListener(ChildEventListener eventListener,String key) { mapListners.put(key,eventListener); } } 

and add this to your Manifest.xml file

 <application android:name=".MApplication" android:icon="@drawable/icon" android:label="@string/app_name"> 
0
source

Try Firebase cloud messaging with Firebase features.

0
source

All Articles