Search code examples
androidfirebasefirebase-realtime-databaseandroid-workmanager

How to run worker manager even after the app has been destroyed


This the code I wrote so far but it doesn't run when the activity is destroyed. I want to listen to any changes in my firebase and save it in an array, it works when the activity is onPause or onStop when is destroyed it does show any update in the logs

public class FirebaseSectionWorker extends Worker {

    final String TAG = "FirebaseBackground";

    private DatabaseReference mDatabase;


    public FirebaseSectionWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
    }

    @Override
    public void onStopped() {
        super.onStopped();

        Log.d(TAG, "onStopped: Firebase listener stopped");

    }

    @NonNull
    @Override
    public Result doWork() {
        Log.d(TAG, "doWork(): Has started to run in the background");


        //Database reference
        mDatabase = FirebaseDatabase.getInstance().getReference().child("users");


        mDatabase.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {


            }

            @Override
            public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
                Log.d(TAG, "onChildChanged(): A child has been changed: " + dataSnapshot);
            }

            @Override
            public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

        return Result.success();
    }
}

Solution

  • WorkManager isn't for work that must stay active in the background indefinitely, so it won't work for things like Firebase listeners. The best you can do is set up a foreground service, but even that can get killed in some situations.

    If you have new data to send to your client app, you should consider instead sending that with Firebase Cloud Messaging, which will wake your app in order to deliver the message.