Cancel unique periodic work from within the Worker class for a unique set of data

Viewed 131

I have a Worker class where I am executing the logic of the scheduled periodic work request inside the doWork() method. However, after a certain condition is met inside the doWork() condition, I want to cancel that work for that particular unique set of data. How can I achieve that? Currently, I am using enqueueUniquePeriodicWork to enqueue the work and cancelUniqueWork to cancel it, however, it is inside my activity, and since I want the task to be cancelled even when I am not on the particular activity, I would need to schedule it in the Worker class so that it happens in background regardless.

PeriodicWorkRequest instance in my activity

    Data data = new Data.Builder()
            .putString("fl", flightNumber)
            .putString("d", departure_date)
            .putString("deptime",final_departure_time_correct_format).build();

    String unique_notification_request = data.toString();

    final PeriodicWorkRequest periodicWorkRequest1 = new PeriodicWorkRequest.Builder(SendNotification.class,15, TimeUnit.MINUTES)
            .setInputData(data)
            .build();

    WorkManager workManager =  WorkManager.getInstance(FlightDescriptionActivity.this);

    workManager.enqueueUniquePeriodicWork(unique_notification_request,ExistingPeriodicWorkPolicy.REPLACE, periodicWorkRequest1);

    workManager.cancelUniqueWork(unique_notification_request);

    workManager.getWorkInfoByIdLiveData(periodicWorkRequest1.getId())
                .observe(FlightDescriptionActivity.this, new Observer<WorkInfo>() {
                        @Override
                        public void onChanged(@Nullable WorkInfo workInfo) {
                                if (workInfo != null) {
                                Log.d("periodicWorkRequest", "Status changed to : " + workInfo.getState());
                        
              }
           }
      });

Worker class

public class SendNotification extends Worker {
    private FlightRepository flightRepo;
    public Context context;
    DateTimeFormatter formatter;
    LocalDateTime final_departure_time;


    public SendNotification(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
        this.flightRepo = new FlightRepository(context);
    }


    @RequiresApi(api = Build.VERSION_CODES.O)
    @NonNull
    @Override
    public Result doWork() {
        String flightnumber = getInputData().getString("fl");
        String date = getInputData().getString("d");
        String time = getInputData().getString("deptime");
        formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

        final_departure_time = LocalDateTime.parse(time, formatter);

        String current_time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
        LocalDateTime current_time_now = LocalDateTime.parse(current_time, formatter);

        long totaldiffInMinutes = Duration.between(final_departure_time, current_time_now).toMinutes();
        
        if(!(flightnumber==null || date == null || time ==null ) && !(totaldiffInMinutes>=0)){

            Flight flight = flightRepo.getFlight(flightnumber,date);

            long diffInMinutes = Duration.between(time_now, final_departure_time).toMinutes();
            
            if (diffInMinutes < 10) {
                sendNotification("Notif", 'notif', 1 );

            }

        }
        
        
        if(totaldiffInMinutes<0){
            \\I WANT TO CANCEL THE SENDING NOTIFICATIONS WORK FOR THIS FLIGHT HERE
        }
        return Result.success();
    }
0 Answers
Related