Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - How to check if Worker meet Constraints when is enqueued?

How can I check if the Worker meets Constraints when is enqueued?

For example, if I need to download data from the internet and establish that the Worker only runs if there is an internet connection. How can I check at that moment if the Worker meet the Constraints to alert the user?

Or if I'm going to perform a task that can consume a lot of battery power and I want to show a Dialog saying "Start charging your Smartphone's battery to start"

Is there a way to do it from the WorkManager or do I have to do it from an external method?

like image 827
Oscar Méndez Avatar asked Oct 16 '22 17:10

Oscar Méndez


2 Answers

I think there should be some sort of callback provided by the library for when constraint(s) are not met (currently there is nothing like that).

I created a google issue here: https://issuetracker.google.com/issues/144367861

Feel free to star it so it can get more visibility :)

like image 161
Alessandro Mautone Avatar answered Oct 20 '22 22:10

Alessandro Mautone


USE getWorkInfoByIdLiveData().observe()

WorkManager.getInstance().enqueue(WorkRequest);

WorkManager.getInstance().getWorkInfoByIdLiveData(WorkRequest.getId())
    .observe(this, new Observer<WorkInfo>() {
        @Override
            public void onChanged(WorkInfo workInfo) {

                switch (workInfo.getState()) {
                    case ENQUEUED:
                        // TODO: Show alert here
                        break;
                    case RUNNING:
                        // TODO: Remove alert, if running 
                        break;
                    case SUCCEEDED:
                        // TODO: After work completed
                        break;
                    case FAILED:
                        break;
                    case BLOCKED:
                        break;
                    case CANCELLED:
                        break;
                }
            }
        });

WorkInfo.State has 6 states, ENQUEUED can be useful for you.

like image 44
Hassan Naqvi Avatar answered Oct 20 '22 21:10

Hassan Naqvi