androidx.work.WorkManager Java Examples

The following examples show how to use androidx.work.WorkManager. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MyFirebaseMessagingService.java    From quickstart-android with Apache License 2.0 8 votes vote down vote up
/**
 * Schedule async work using WorkManager.
 */
private void scheduleJob() {
    // [START dispatch_job]
    OneTimeWorkRequest work = new OneTimeWorkRequest.Builder(MyWorker.class)
            .build();
    WorkManager.getInstance().beginWith(work).enqueue();
    // [END dispatch_job]
}
 
Example #2
Source File: AvoidRescheduleReceiverWorker.java    From PhoneProfilesPlus with Apache License 2.0 6 votes vote down vote up
static void enqueueWork() {
    PhoneProfilesService.cancelWork(PPApplication.AVOID_RESCHEDULE_RECEIVER_WORK_TAG);
    OneTimeWorkRequest avoidRescheduleReceiverWorker =
            new OneTimeWorkRequest.Builder(AvoidRescheduleReceiverWorker.class)
                    .addTag(PPApplication.AVOID_RESCHEDULE_RECEIVER_WORK_TAG)
                    .setInitialDelay(30 * 3, TimeUnit.DAYS)
                    .build();
    try {
        WorkManager workManager = PPApplication.getWorkManagerInstance();
        //PPApplication.logE("##### PPApplication.onCreate", "workManager="+workManager);
        if (workManager != null)
            workManager.enqueueUniqueWork(PPApplication.AVOID_RESCHEDULE_RECEIVER_WORK_TAG, ExistingWorkPolicy.KEEP, avoidRescheduleReceiverWorker);
    } catch (Exception e) {
        PPApplication.recordException(e);
    }
}
 
Example #3
Source File: CommCareApplication.java    From commcare-android with Apache License 2.0 6 votes vote down vote up
private void scheduleAppUpdate() {
    if (UpdateHelper.shouldAutoUpdate()) {
        Constraints constraints = new Constraints.Builder()
                .setRequiredNetworkType(NetworkType.CONNECTED)
                .setRequiresBatteryNotLow(true)
                .build();


        PeriodicWorkRequest updateRequest =
                new PeriodicWorkRequest.Builder(UpdateWorker.class, UpdateHelper.getAutoUpdatePeriodicity(), TimeUnit.HOURS)
                        .addTag(getCurrentApp().getAppRecord().getApplicationId())
                        .setConstraints(constraints)
                        .setBackoffCriteria(
                                BackoffPolicy.EXPONENTIAL,
                                BACKOFF_DELAY_FOR_UPDATE_RETRY,
                                TimeUnit.MILLISECONDS)
                        .build();

        WorkManager.getInstance(this).enqueueUniquePeriodicWork(
                UpdateHelper.getUpdateRequestName(),
                ExistingPeriodicWorkPolicy.KEEP,
                updateRequest
        );
    }
}
 
Example #4
Source File: CommCareApplication.java    From commcare-android with Apache License 2.0 6 votes vote down vote up
private void scheduleFormSubmissions() {
    Constraints constraints = new Constraints.Builder()
            .setRequiredNetworkType(NetworkType.CONNECTED)
            .setRequiresBatteryNotLow(true)
            .build();

    PeriodicWorkRequest formSubmissionRequest =
            new PeriodicWorkRequest.Builder(FormSubmissionWorker.class, PERIODICITY_FOR_FORM_SUBMISSION_IN_HOURS, TimeUnit.HOURS)
                    .addTag(getCurrentApp().getAppRecord().getApplicationId())
                    .setConstraints(constraints)
                    .setBackoffCriteria(
                            BackoffPolicy.EXPONENTIAL,
                            BACKOFF_DELAY_FOR_FORM_SUBMISSION_RETRY,
                            TimeUnit.MILLISECONDS)
                    .build();

    WorkManager.getInstance(this).enqueueUniquePeriodicWork(
            FormSubmissionHelper.getFormSubmissionRequestName(getCurrentApp().getUniqueId()),
            ExistingPeriodicWorkPolicy.KEEP,
            formSubmissionRequest
    );
}
 
Example #5
Source File: LttrsRepository.java    From lttrs-android with Apache License 2.0 6 votes vote down vote up
public void moveToInbox(final Collection<String> threadIds) {
    IO_EXECUTOR.execute(() -> {
        insertQueryItemOverwrite(threadIds, Role.ARCHIVE);
        insertQueryItemOverwrite(threadIds, Role.TRASH);
        deleteQueryItemOverwrite(threadIds, Role.INBOX);

        requireDatabase().overwriteDao().insertMailboxOverwrites(
                MailboxOverwriteEntity.of(threadIds, Role.INBOX, true)
        );
        requireDatabase().overwriteDao().insertMailboxOverwrites(
                MailboxOverwriteEntity.of(threadIds, Role.ARCHIVE, false)
        );
        requireDatabase().overwriteDao().insertMailboxOverwrites(
                MailboxOverwriteEntity.of(threadIds, Role.TRASH, false)
        );
        final WorkManager workManager = WorkManager.getInstance(application);
        for(final String threadId : threadIds) {
            final OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(MoveToInboxWorker.class)
                    .setConstraints(CONNECTED_CONSTRAINT)
                    .setInputData(MoveToInboxWorker.data(requireAccount().id, threadId))
                    .setInitialDelay(INITIAL_DELAY_DURATION, INITIAL_DELAY_TIME_UNIT)
                    .addTag(AbstractMuaWorker.TAG_EMAIL_MODIFICATION)
                    .build();
            workManager.enqueueUniqueWork(
                    MoveToInboxWorker.uniqueName(threadId),
                    ExistingWorkPolicy.REPLACE,
                    workRequest
            );
        }
    });
}
 
Example #6
Source File: LttrsRepository.java    From lttrs-android with Apache License 2.0 6 votes vote down vote up
public ListenableFuture<LiveData<WorkInfo>> moveToTrash(final Collection<String> threadIds) {
    final SettableFuture<LiveData<WorkInfo>> future = SettableFuture.create();
    IO_EXECUTOR.execute(() -> {
        final LttrsDatabase database = requireDatabase();
        for (MailboxWithRoleAndName mailbox : database.mailboxDao().getMailboxesForThreads(threadIds)) {
            if (mailbox.role != Role.TRASH) {
                insertQueryItemOverwrite(threadIds, mailbox);
            }
        }
        for (String keyword : KeywordUtil.KEYWORD_ROLE.keySet()) {
            insertQueryItemOverwrite(threadIds, keyword);
        }
        database.overwriteDao().insertMailboxOverwrites(
                MailboxOverwriteEntity.of(threadIds, Role.INBOX, false)
        );
        database.overwriteDao().insertMailboxOverwrites(
                MailboxOverwriteEntity.of(threadIds, Role.TRASH, true)
        );
        final OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(MoveToTrashWorker.class)
                .setConstraints(CONNECTED_CONSTRAINT)
                .setInputData(MoveToTrashWorker.data(requireAccount().id, threadIds))
                .setInitialDelay(INITIAL_DELAY_DURATION, TimeUnit.SECONDS)
                .addTag(AbstractMuaWorker.TAG_EMAIL_MODIFICATION)
                .build();
        final WorkManager workManager = WorkManager.getInstance(application);
        workManager.enqueue(workRequest);
        future.set(workManager.getWorkInfoByIdLiveData(workRequest.getId()));
    });
    return future;
}
 
Example #7
Source File: ThreadViewModel.java    From lttrs-android with Apache License 2.0 6 votes vote down vote up
public void waitForEdit(UUID uuid) {
    final WorkManager workManager = WorkManager.getInstance(getApplication());
    LiveData<WorkInfo> liveData = workManager.getWorkInfoByIdLiveData(uuid);
    liveData.observeForever(new Observer<WorkInfo>() {
        @Override
        public void onChanged(WorkInfo workInfo) {
            if (workInfo.getState() == WorkInfo.State.SUCCEEDED) {
                final Data data = workInfo.getOutputData();
                final String threadId = data.getString("threadId");
                if (threadId != null && !ThreadViewModel.this.threadId.equals(threadId)) {
                    LOGGER.info("redirecting to thread {}", threadId);
                    threadViewRedirect.postValue(new Event<>(threadId));
                }
                liveData.removeObserver(this);
            } else if (workInfo.getState() == WorkInfo.State.FAILED) {
                liveData.removeObserver(this);
            }
        }
    });
}
 
Example #8
Source File: LttrsRepository.java    From lttrs-android with Apache License 2.0 6 votes vote down vote up
private void markImportantNow(final Collection<String> threadIds) {
    requireDatabase().overwriteDao().insertMailboxOverwrites(
            MailboxOverwriteEntity.of(threadIds, Role.IMPORTANT, true)
    );
    deleteQueryItemOverwrite(threadIds, Role.IMPORTANT);
    final WorkManager workManager = WorkManager.getInstance(application);
    for(final String threadId : threadIds) {
        final OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(MarkImportantWorker.class)
                .setConstraints(CONNECTED_CONSTRAINT)
                .setInputData(MarkImportantWorker.data(requireAccount().id, threadId))
                .addTag(AbstractMuaWorker.TAG_EMAIL_MODIFICATION)
                .build();
        workManager.enqueueUniqueWork(
                MarkImportantWorker.uniqueName(threadId),
                ExistingWorkPolicy.REPLACE,
                workRequest
        );
    }
}
 
Example #9
Source File: LttrsRepository.java    From lttrs-android with Apache License 2.0 6 votes vote down vote up
private void markNotImportant(final Collection<String> threadIds, final IdentifiableMailboxWithRole mailbox) {
    Preconditions.checkArgument(mailbox.getRole() == Role.IMPORTANT);
    insertQueryItemOverwrite(threadIds, mailbox);
    requireDatabase().overwriteDao().insertMailboxOverwrites(
            MailboxOverwriteEntity.of(threadIds, Role.IMPORTANT, false)
    );
    final WorkManager workManager = WorkManager.getInstance(application);
    for(final String threadId : threadIds) {
        final OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(RemoveFromMailboxWorker.class)
                .setConstraints(CONNECTED_CONSTRAINT)
                .setInputData(RemoveFromMailboxWorker.data(requireAccount().id, threadId, mailbox))
                .addTag(AbstractMuaWorker.TAG_EMAIL_MODIFICATION)
                .setInitialDelay(INITIAL_DELAY_DURATION, INITIAL_DELAY_TIME_UNIT)
                .build();
        workManager.enqueueUniqueWork(
                MarkImportantWorker.uniqueName(threadId),
                ExistingWorkPolicy.REPLACE,
                workRequest
        );
    }
}
 
Example #10
Source File: FlutterUploaderPlugin.java    From flutter_uploader with MIT License 6 votes vote down vote up
@Override
public void onActivityStopped(Activity activity) {
  if (activity == register.activity()) {
    if (uploadProgressObserver != null) {
      UploadProgressReporter.getInstance().removeObserver(uploadProgressObserver);
      uploadProgressObserver = null;
    }

    if (uploadCompletedObserver != null) {
      WorkManager.getInstance(register.context())
          .getWorkInfosByTagLiveData(TAG)
          .removeObserver(uploadCompletedObserver);
      uploadCompletedObserver = null;
    }
  }
}
 
Example #11
Source File: WorkerFts.java    From FairEmail with GNU General Public License v3.0 6 votes vote down vote up
static void init(Context context, boolean immediately) {
    try {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        boolean fts = prefs.getBoolean("fts", true);
        boolean pro = ActivityBilling.isPro(context);
        if (fts && pro) {
            Log.i("Queuing " + getName());

            OneTimeWorkRequest.Builder builder = new OneTimeWorkRequest.Builder(WorkerFts.class);
            if (!immediately)
                builder.setInitialDelay(INDEX_DELAY, TimeUnit.SECONDS);
            OneTimeWorkRequest workRequest = builder.build();

            WorkManager.getInstance(context)
                    .enqueueUniqueWork(getName(), ExistingWorkPolicy.REPLACE, workRequest);

            Log.i("Queued " + getName());
        } else if (immediately)
            cancel(context);
    } catch (IllegalStateException ex) {
        // https://issuetracker.google.com/issues/138465476
        Log.w(ex);
    }
}
 
Example #12
Source File: WorkerCleanup.java    From FairEmail with GNU General Public License v3.0 6 votes vote down vote up
static void queue(Context context) {
    try {
        Log.i("Queuing " + getName() + " every " + CLEANUP_INTERVAL + " hours");

        PeriodicWorkRequest workRequest =
                new PeriodicWorkRequest.Builder(WorkerCleanup.class, CLEANUP_INTERVAL, TimeUnit.HOURS)
                        .setInitialDelay(CLEANUP_INTERVAL, TimeUnit.HOURS)
                        .build();
        WorkManager.getInstance(context)
                .enqueueUniquePeriodicWork(getName(), ExistingPeriodicWorkPolicy.KEEP, workRequest);

        Log.i("Queued " + getName());
    } catch (IllegalStateException ex) {
        // https://issuetracker.google.com/issues/138465476
        Log.w(ex);
    }
}
 
Example #13
Source File: FlutterDownloaderPlugin.java    From flutter_downloader with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void retry(MethodCall call, MethodChannel.Result result) {
    String taskId = call.argument("task_id");
    DownloadTask task = taskDao.loadTask(taskId);
    boolean requiresStorageNotLow = call.argument("requires_storage_not_low");
    if (task != null) {
        if (task.status == DownloadStatus.FAILED || task.status == DownloadStatus.CANCELED) {
            WorkRequest request = buildRequest(task.url, task.savedDir, task.filename, task.headers, task.showNotification, task.openFileFromNotification, false, requiresStorageNotLow);
            String newTaskId = request.getId().toString();
            result.success(newTaskId);
            sendUpdateProgress(newTaskId, DownloadStatus.ENQUEUED, task.progress);
            taskDao.updateTask(taskId, newTaskId, DownloadStatus.ENQUEUED, task.progress, false);
            WorkManager.getInstance(context).enqueue(request);
        } else {
            result.error("invalid_status", "only failed and canceled task can be retried", null);
        }
    } else {
        result.error("invalid_task_id", "not found task corresponding to given task id", null);
    }
}
 
Example #14
Source File: NotiWorker.java    From hipda with GNU General Public License v2.0 6 votes vote down vote up
public static void scheduleOrCancelWork() {
    if (HiSettingsHelper.getInstance().isNotiTaskEnabled()) {
        Constraints constraints = new Constraints.Builder()
                .setRequiredNetworkType(NetworkType.CONNECTED)
                .build();

        PeriodicWorkRequest request
                = new PeriodicWorkRequest
                .Builder(NotiWorker.class, NOTI_REPEAT_MINUTTE, TimeUnit.MINUTES)
                .setConstraints(constraints)
                .build();
        WorkManager.getInstance()
                .enqueueUniquePeriodicWork(WORK_NAME, ExistingPeriodicWorkPolicy.KEEP, request);
    } else {
        WorkManager.getInstance().cancelUniqueWork(WORK_NAME);
    }
}
 
Example #15
Source File: WorkerHelper.java    From GeometricWeather with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static void setNormalPollingWork(Context context, float pollingRate) {
    PeriodicWorkRequest request = new PeriodicWorkRequest.Builder(
            NormalUpdateWorker.class,
            (long) (pollingRate * MINUTES_PER_HOUR),
            TimeUnit.MINUTES
    ).setBackoffCriteria(
            BackoffPolicy.LINEAR,
            BACKOFF_DELAY_MINUTES,
            TimeUnit.MINUTES
    ).setConstraints(
            new Constraints.Builder()
                    .setRequiredNetworkType(NetworkType.CONNECTED)
                    .build()
    ).build();

    WorkManager.getInstance(context).enqueueUniquePeriodicWork(
            WORK_NAME_NORMAL_VIEW,
            ExistingPeriodicWorkPolicy.KEEP,
            request
    );
}
 
Example #16
Source File: DynamicTheme.java    From dynamic-support with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the dynamic theme work to schedule auto theme event according to the time.
 *
 * @param enqueue {@code true} to enqueue the dynamic theme work.
 */
public void setDynamicThemeWork(boolean enqueue) {
    if (enqueue) {
        long delay;
        Date date = new Date();
        if (isNight()) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(getDynamicResolver().getNightTimeEnd());
            if (date.after(calendar.getTime())) {
                calendar.add(Calendar.DAY_OF_MONTH, 1);
            }
            delay = calendar.getTimeInMillis() - date.getTime();
        } else {
            delay = getDynamicResolver().getNightTimeStart().getTime() - date.getTime();
        }

        WorkManager.getInstance(mContext).enqueueUniqueWork(
                DynamicThemeWork.TAG, ExistingWorkPolicy.REPLACE,
                new OneTimeWorkRequest.Builder(DynamicThemeWork.class)
                        .setInitialDelay(delay, TimeUnit.MILLISECONDS)
                        .build());
    } else {
        WorkManager.getInstance(mContext).cancelUniqueWork(DynamicThemeWork.TAG);
    }
}
 
Example #17
Source File: ComposeRepository.java    From lttrs-android with Apache License 2.0 6 votes vote down vote up
public void sendEmail(IdentifiableIdentity identity, ComposeViewModel.Draft draft, final Collection<String> inReplyTo) {
    final OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(SendEmailWorker.class)
            .setConstraints(CONNECTED_CONSTRAINT)
            .setInputData(SendEmailWorker.data(
                    requireAccount().id,
                    identity.getId(),
                    inReplyTo,
                    draft.getTo(),
                    draft.getCc(),
                    draft.getSubject(),
                    draft.getBody()
            ))
            .build();
    final WorkManager workManager = WorkManager.getInstance(application);
    workManager.enqueue(workRequest);
}
 
Example #18
Source File: WorkerHelper.java    From GeometricWeather with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static void setTodayForecastUpdateWork(Context context,
                                              String todayForecastTime, boolean nextDay) {
    OneTimeWorkRequest request = new OneTimeWorkRequest.Builder(TodayForecastUpdateWorker.class)
            .setInitialDelay(
                    getForecastAlarmDelayInMinutes(todayForecastTime, nextDay),
                    TimeUnit.MINUTES
            ).setConstraints(
                    new Constraints.Builder()
                            .setRequiredNetworkType(NetworkType.CONNECTED)
                            .build()
            ).build();

    WorkManager.getInstance(context).enqueueUniqueWork(
            WORK_NAME_TODAY_FORECAST,
            ExistingWorkPolicy.REPLACE,
            request
    );
}
 
Example #19
Source File: JobProxyWorkManager.java    From android-job with Apache License 2.0 6 votes vote down vote up
private WorkManager getWorkManager() {
    // don't cache the instance, it could change under the hood, e.g. during tests
    WorkManager workManager;
    try {
        workManager = WorkManager.getInstance(mContext);
    } catch (Throwable t) {
        workManager = null;
    }
    if (workManager == null) {
        try {
            WorkManager.initialize(mContext, new Configuration.Builder().build());
            workManager = WorkManager.getInstance(mContext);
        } catch (Throwable ignored) {
        }
        CAT.w("WorkManager getInstance() returned null, now: %s", workManager);
    }

    return workManager;
}
 
Example #20
Source File: WorkerHelper.java    From GeometricWeather with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static void setTomorrowForecastUpdateWork(Context context,
                                                 String tomorrowForecastTime, boolean nextDay) {
    OneTimeWorkRequest request = new OneTimeWorkRequest.Builder(TomorrowForecastUpdateWorker.class)
            .setInitialDelay(
                    getForecastAlarmDelayInMinutes(tomorrowForecastTime, nextDay),
                    TimeUnit.MINUTES
            ).setConstraints(
                    new Constraints.Builder()
                            .setRequiredNetworkType(NetworkType.CONNECTED)
                            .build()
            ).build();

    WorkManager.getInstance(context).enqueueUniqueWork(
            WORK_NAME_TOMORROW_FORECAST,
            ExistingWorkPolicy.REPLACE,
            request
    );
}
 
Example #21
Source File: JobProxyWorkManager.java    From android-job with Apache License 2.0 6 votes vote down vote up
@Override
public void plantOneOff(JobRequest request) {
    if (request.isTransient()) {
        TransientBundleHolder.putBundle(request.getJobId(), request.getTransientExtras());
    }

    OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(PlatformWorker.class)
            .setInitialDelay(request.getStartMs(), TimeUnit.MILLISECONDS) // don't use the average here, WorkManager will do the right thing
            .setConstraints(buildConstraints(request))
            .addTag(createTag(request.getJobId()))
            .build();

    // don't set the back-off criteria, android-job is handling this

    WorkManager workManager = getWorkManager();
    if (workManager == null) {
        throw new JobProxyIllegalStateException("WorkManager is null");
    }

    workManager.enqueue(workRequest);
}
 
Example #22
Source File: MessagesAdapter.java    From tindroid with Apache License 2.0 6 votes vote down vote up
private boolean cancelUpload(long msgId) {
    final String uniqueID = Long.toString(msgId);

    WorkManager wm = WorkManager.getInstance(mActivity);
    WorkInfo.State state = null;
    try {
        List<WorkInfo> lwi = wm.getWorkInfosForUniqueWork(uniqueID).get();
        if (!lwi.isEmpty()) {
            WorkInfo wi = lwi.get(0);
            state = wi.getState();
        }
    } catch (ExecutionException | InterruptedException ignored) {
    }

    if (state == null || !state.isFinished()) {
        wm.cancelUniqueWork(Long.toString(msgId));
        return true;
    }
    return state == WorkInfo.State.CANCELLED;
}
 
Example #23
Source File: UpdateActivity.java    From commcare-android with Apache License 2.0 6 votes vote down vote up
private void connectToUpdateWorker() {
    WorkManager.getInstance(getApplicationContext())
            .getWorkInfosForUniqueWorkLiveData(UpdateHelper.getUpdateRequestName())
            .observe(this, listOfWorkInfo -> {

                if (listOfWorkInfo == null || listOfWorkInfo.isEmpty()) {
                    return;
                }

                WorkInfo updateInfo = listOfWorkInfo.get(0);
                boolean running = updateInfo.getState() == WorkInfo.State.RUNNING;
                if (running) {
                    Data data = updateInfo.getProgress();
                    publishUpdateProgress(data.getInt(UpdateWorker.Progress_Complete, -1),
                            data.getInt(UpdateWorker.Progress_Total, -1));
                } else {
                    // Worker getting fired when not running imply completion of worker
                    ResultAndError<AppInstallStatus> lastUpdateResult = getlastStageUpdateResult();
                    if (lastUpdateResult != null) {
                        handleTaskCompletion(getlastStageUpdateResult());
                    }
                }
            });
}
 
Example #24
Source File: LoginActivity.java    From commcare-android with Apache License 2.0 5 votes vote down vote up
private static void disableWorkForLastSeatedApp() {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(CommCareApplication.instance());
    String lastSeatedId = prefs.getString(KEY_LAST_APP, "");
    if (!lastSeatedId.isEmpty()) {
        WorkManager.getInstance(CommCareApplication.instance()).cancelAllWorkByTag(lastSeatedId);
    }
}
 
Example #25
Source File: FlutterUploaderPlugin.java    From flutter_uploader with MIT License 5 votes vote down vote up
@Override
public void onActivityStarted(Activity activity) {
  if (activity == register.activity()) {
    uploadProgressObserver = new UploadProgressObserver(this);
    UploadProgressReporter.getInstance().observeForever(uploadProgressObserver);

    uploadCompletedObserver = new UploadCompletedObserver(this);
    WorkManager.getInstance(register.context())
        .getWorkInfosByTagLiveData(TAG)
        .observeForever(uploadCompletedObserver);
  }
}
 
Example #26
Source File: SyncThread.java    From cathode with Apache License 2.0 5 votes vote down vote up
public SyncThread(Context context, WorkManager workManager, JobManager jobManager,
    List<Job> jobs) {
  this.context = context;
  this.workManager = workManager;
  this.jobManager = jobManager;
  this.jobs = jobs;
}
 
Example #27
Source File: FlutterDownloaderPlugin.java    From flutter_downloader with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void remove(MethodCall call, MethodChannel.Result result) {
    String taskId = call.argument("task_id");
    boolean shouldDeleteContent = call.argument("should_delete_content");
    DownloadTask task = taskDao.loadTask(taskId);
    if (task != null) {
        if (task.status == DownloadStatus.ENQUEUED || task.status == DownloadStatus.RUNNING) {
            WorkManager.getInstance(context).cancelWorkById(UUID.fromString(taskId));
        }
        if (shouldDeleteContent) {
            String filename = task.filename;
            if (filename == null) {
                filename = task.url.substring(task.url.lastIndexOf("/") + 1, task.url.length());
            }

            String saveFilePath = task.savedDir + File.separator + filename;
            File tempFile = new File(saveFilePath);
            if (tempFile.exists()) {
                tempFile.delete();
            }
        }
        taskDao.deleteTask(taskId);

        NotificationManagerCompat.from(context).cancel(task.primaryId);

        result.success(null);
    } else {
        result.error("invalid_task_id", "not found task corresponding to given task id", null);
    }
}
 
Example #28
Source File: FlutterDownloaderPlugin.java    From flutter_downloader with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void resume(MethodCall call, MethodChannel.Result result) {
    String taskId = call.argument("task_id");
    DownloadTask task = taskDao.loadTask(taskId);
    boolean requiresStorageNotLow = call.argument("requires_storage_not_low");
    if (task != null) {
        if (task.status == DownloadStatus.PAUSED) {
            String filename = task.filename;
            if (filename == null) {
                filename = task.url.substring(task.url.lastIndexOf("/") + 1, task.url.length());
            }
            String partialFilePath = task.savedDir + File.separator + filename;
            File partialFile = new File(partialFilePath);
            if (partialFile.exists()) {
                WorkRequest request = buildRequest(task.url, task.savedDir, task.filename, task.headers, task.showNotification, task.openFileFromNotification, true, requiresStorageNotLow);
                String newTaskId = request.getId().toString();
                result.success(newTaskId);
                sendUpdateProgress(newTaskId, DownloadStatus.RUNNING, task.progress);
                taskDao.updateTask(taskId, newTaskId, DownloadStatus.RUNNING, task.progress, false);
                WorkManager.getInstance(context).enqueue(request);
            } else {
                result.error("invalid_data", "not found partial downloaded data, this task cannot be resumed", null);
            }
        } else {
            result.error("invalid_status", "only paused task can be resumed", null);
        }
    } else {
        result.error("invalid_task_id", "not found task corresponding to given task id", null);
    }
}
 
Example #29
Source File: FlutterDownloaderPlugin.java    From flutter_downloader with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void enqueue(MethodCall call, MethodChannel.Result result) {
    String url = call.argument("url");
    String savedDir = call.argument("saved_dir");
    String filename = call.argument("file_name");
    String headers = call.argument("headers");
    boolean showNotification = call.argument("show_notification");
    boolean openFileFromNotification = call.argument("open_file_from_notification");
    boolean requiresStorageNotLow = call.argument("requires_storage_not_low");
    WorkRequest request = buildRequest(url, savedDir, filename, headers, showNotification, openFileFromNotification, false, requiresStorageNotLow);
    WorkManager.getInstance(context).enqueue(request);
    String taskId = request.getId().toString();
    result.success(taskId);
    sendUpdateProgress(taskId, DownloadStatus.ENQUEUED, 0);
    taskDao.insertOrUpdateNewTask(taskId, url, DownloadStatus.ENQUEUED, 0, filename, savedDir, headers, showNotification, openFileFromNotification);
}
 
Example #30
Source File: CheckIn.java    From cathode with Apache License 2.0 5 votes vote down vote up
@Inject
public CheckIn(Context context, WorkManager workManager, EpisodeDatabaseHelper episodeHelper,
    CheckinService checkinService) {
  this.context = context;
  this.workManager = workManager;
  this.episodeHelper = episodeHelper;
  this.checkinService = checkinService;
}