How to use Room database in a background service

Viewed 26

I need to access my repository in a service. This is how I instantiate the repository in a ViewModel

public MainMenuViewModel(@NonNull @NotNull Application application) {
    super(application);
    pendingTransactionRepository = new PendingTransactionRepository(application);
}

I have access to the "Application" so this is no problem for me.But when I use this repository in a background service, I get the "Application" from this part of the background service:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    mApplication = getApplication();
    pendingTransactionRepository = new PendingTransactionRepository(mApplication);

    setupLiveData();
    return super.onStartCommand(intent, flags, startId);
}

In my fragment, I can easily do setup this by doing it this way:

pendingTransactionRepository.pendingTransactionBySendStatus().observe(getActivity(), new Observer<List<PendingTransaction>>() {
        @Override
        public void onChanged(List<PendingTransaction> pendingTransactions) {
            int count = pendingTransactions.size();
            Log.i("LOG", String.valueOf(count));
        }
    });
}

But in a service, I do not know what to put in the "LifeCycleOwner" part.

pendingTransactionRepository.pendingTransactionBySendStatus().observe("WHAT_DO_I_PUT_HERE", new Observer<List<PendingTransaction>>() {
        @Override
        public void onChanged(List<PendingTransaction> pendingTransactions) {
            int count = pendingTransactions.size();
            Log.i("LOG", String.valueOf(count));
        }
    });
}
1 Answers

You can use a LifecycleService which implements a LifecycleOwner.
Add this dependency in your app's build.gradle:

implementation 'androidx.lifecycle:lifecycle-service:2.5.1'

And make your Service extend LifecycleService like:

public class BackendService extends LifecycleService {

    @Override
    public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
        mApplication = getApplication();
        pendingTransactionRepository = new PendingTransactionRepository(mApplication);

        pendingTransactionRepository.pendingTransactionBySendStatus().observe(this, new Observer<List<PendingTransaction>>() {
            @Override
            public void onChanged(List<PendingTransaction> pendingTransactions) {
                int count = pendingTransactions.size();
                Log.i("LOG", String.valueOf(count));
            }
        });

        return super.onStartCommand(intent, flags, startId);
    }
}
Related