即使应用程序被销毁后如何运行工作者管理器

这是我到目前为止编写的代码,但是在销毁活动时它无法运行。我想听我的Firebase中的任何更改并将其保存在数组中,当活动处于onPause或onStop销毁时它可以工作,它确实在日志中显示任何更新

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();
    }
}
评论
  • bjstry
    bjstry 回复

    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.

    如果您有新数据要发送到客户端应用程序,则应考虑改为使用Firebase Cloud Messaging发送数据,Firebase Cloud Messaging将唤醒您的应用程序以传递消息。