androidx.work.OneTimeWorkRequest Java Examples

The following examples show how to use androidx.work.OneTimeWorkRequest. 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: MysplashMuzeiWorker.java    From Mysplash with GNU Lesser General Public License v3.0 8 votes vote down vote up
static void enqueue() {
    WorkManager.getInstance().enqueue(
            new OneTimeWorkRequest.Builder(MysplashMuzeiWorker.class).setConstraints(
                    new Constraints.Builder()
                            .setRequiredNetworkType(NetworkType.CONNECTED)
                            .build()
            ).build()
    );
}
 
Example #2
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 #3
Source File: FlutterDownloaderPlugin.java    From flutter_downloader with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
private WorkRequest buildRequest(String url, String savedDir, String filename, String headers, boolean showNotification, boolean openFileFromNotification, boolean isResume, boolean requiresStorageNotLow) {
    WorkRequest request = new OneTimeWorkRequest.Builder(DownloadWorker.class)
            .setConstraints(new Constraints.Builder()
                    .setRequiresStorageNotLow(requiresStorageNotLow)
                    .setRequiredNetworkType(NetworkType.CONNECTED)
                    .build())
            .addTag(TAG)
            .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 5, TimeUnit.SECONDS)
            .setInputData(new Data.Builder()
                    .putString(DownloadWorker.ARG_URL, url)
                    .putString(DownloadWorker.ARG_SAVED_DIR, savedDir)
                    .putString(DownloadWorker.ARG_FILE_NAME, filename)
                    .putString(DownloadWorker.ARG_HEADERS, headers)
                    .putBoolean(DownloadWorker.ARG_SHOW_NOTIFICATION, showNotification)
                    .putBoolean(DownloadWorker.ARG_OPEN_FILE_FROM_NOTIFICATION, openFileFromNotification)
                    .putBoolean(DownloadWorker.ARG_IS_RESUME, isResume)
                    .putLong(DownloadWorker.ARG_CALLBACK_HANDLE, callbackHandle)
                    .putBoolean(DownloadWorker.ARG_DEBUG, debugMode == 1)
                    .build()
            )
            .build();
    return request;
}
 
Example #4
Source File: DataSyncWorkManager.java    From ground-android with Apache License 2.0 7 votes vote down vote up
private OneTimeWorkRequest buildWorkerRequest(String featureId) {
  return new OneTimeWorkRequest.Builder(LocalMutationSyncWorker.class)
      .setConstraints(getWorkerConstraints())
      .setBackoffCriteria(BackoffPolicy.LINEAR, SYNC_BACKOFF_MILLIS, TimeUnit.MILLISECONDS)
      .setInputData(LocalMutationSyncWorker.createInputData(featureId))
      .build();
}
 
Example #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #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: 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 #13
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 #14
Source File: ComposeRepository.java    From lttrs-android with Apache License 2.0 6 votes vote down vote up
public boolean discard(EditableEmail editableEmail) {
    final OneTimeWorkRequest discardDraft = new OneTimeWorkRequest.Builder(DiscardDraftWorker.class)
            .setConstraints(CONNECTED_CONSTRAINT)
            .setInputData(DiscardDraftWorker.data(requireAccount().id, editableEmail.id))
            .build();
    final WorkManager workManager = WorkManager.getInstance(application);
    final boolean isOnlyEmailInThread = editableEmail.isOnlyEmailInThread();
    if (isOnlyEmailInThread) {
        insertQueryItemOverwrite(editableEmail.threadId);
    }
    workManager.enqueue(discardDraft);
    return isOnlyEmailInThread;
}
 
Example #15
Source File: LttrsRepository.java    From lttrs-android with Apache License 2.0 6 votes vote down vote up
public void removeFromMailbox(final Collection<String> threadIds, final IdentifiableMailboxWithRole mailbox) {
    IO_EXECUTOR.execute(() -> {
        if (mailbox.getRole() == Role.IMPORTANT) {
            markNotImportant(threadIds, mailbox);
            return;
        }
        insertQueryItemOverwrite(threadIds, mailbox);
        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))
                    .setInitialDelay(INITIAL_DELAY_DURATION, INITIAL_DELAY_TIME_UNIT)
                    .addTag(AbstractMuaWorker.TAG_EMAIL_MODIFICATION)
                    .build();
            workManager.enqueueUniqueWork(
                    RemoveFromMailboxWorker.uniqueName(threadId, mailbox),
                    ExistingWorkPolicy.REPLACE,
                    workRequest
            );
        }
    });
}
 
Example #16
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 #17
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 #18
Source File: LttrsRepository.java    From lttrs-android with Apache License 2.0 6 votes vote down vote up
public void copyToMailbox(@NonNull final Collection<String> threadIds, @NonNull final IdentifiableMailboxWithRole mailbox) {
    IO_EXECUTOR.execute(() -> {
        if (mailbox.getRole() == Role.IMPORTANT) {
            markImportantNow(threadIds);
            return;
        }
        deleteQueryItemOverwrite(threadIds, mailbox);
        final WorkManager workManager = WorkManager.getInstance(application);
        for(final String threadId : threadIds) {
            final OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(CopyToMailboxWorker.class)
                    .setConstraints(CONNECTED_CONSTRAINT)
                    .setInputData(CopyToMailboxWorker.data(requireAccount().id, threadId, mailbox))
                    .addTag(AbstractMuaWorker.TAG_EMAIL_MODIFICATION)
                    .build();
            workManager.enqueueUniqueWork(
                    CopyToMailboxWorker.uniqueName(threadId, mailbox),
                    ExistingWorkPolicy.REPLACE,
                    workRequest
            );
        }
    });
}
 
Example #19
Source File: LttrsRepository.java    From lttrs-android with Apache License 2.0 6 votes vote down vote up
public void archive(final Collection<String> threadIds) {
    IO_EXECUTOR.execute(() -> {
        insertQueryItemOverwrite(threadIds, Role.INBOX);
        deleteQueryItemOverwrite(threadIds, Role.ARCHIVE);
        requireDatabase().overwriteDao().insertMailboxOverwrites(MailboxOverwriteEntity.of(threadIds, Role.INBOX, false));
        requireDatabase().overwriteDao().insertMailboxOverwrites(MailboxOverwriteEntity.of(threadIds, Role.ARCHIVE, true));
        final WorkManager workManager = WorkManager.getInstance(application);
        for(final String threadId : threadIds) {
            final OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(ArchiveWorker.class)
                    .setConstraints(CONNECTED_CONSTRAINT)
                    .setInputData(ArchiveWorker.data(requireAccount().id, threadId))
                    .setInitialDelay(INITIAL_DELAY_DURATION, INITIAL_DELAY_TIME_UNIT)
                    .addTag(AbstractMuaWorker.TAG_EMAIL_MODIFICATION)
                    .build();

            workManager.enqueueUniqueWork(
                    ArchiveWorker.uniqueName(threadId),
                    ExistingWorkPolicy.REPLACE,
                    workRequest
            );
        }
    });
}
 
Example #20
Source File: FlutterUploaderPlugin.java    From flutter_uploader with MIT License 5 votes vote down vote up
private WorkRequest buildRequest(UploadTask task) {
  Gson gson = new Gson();

  Data.Builder dataBuilder =
      new Data.Builder()
          .putString(UploadWorker.ARG_URL, task.getURL())
          .putString(UploadWorker.ARG_METHOD, task.getMethod())
          .putInt(UploadWorker.ARG_REQUEST_TIMEOUT, task.getTimeout())
          .putBoolean(UploadWorker.ARG_SHOW_NOTIFICATION, task.canShowNotification())
          .putBoolean(UploadWorker.ARG_BINARY_UPLOAD, task.isBinaryUpload())
          .putString(UploadWorker.ARG_UPLOAD_REQUEST_TAG, task.getTag())
          .putInt(UploadWorker.ARG_ID, task.getId());

  List<FileItem> files = task.getFiles();

  String fileItemsJson = gson.toJson(files);
  dataBuilder.putString(UploadWorker.ARG_FILES, fileItemsJson);

  if (task.getHeaders() != null) {
    String headersJson = gson.toJson(task.getHeaders());
    dataBuilder.putString(UploadWorker.ARG_HEADERS, headersJson);
  }

  if (task.getParameters() != null) {
    String parametersJson = gson.toJson(task.getParameters());
    dataBuilder.putString(UploadWorker.ARG_DATA, parametersJson);
  }

  return new OneTimeWorkRequest.Builder(UploadWorker.class)
      .setConstraints(
          new Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())
      .addTag(TAG)
      .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 5, TimeUnit.SECONDS)
      .setInputData(dataBuilder.build())
      .build();
}
 
Example #21
Source File: CandyBarArtWorker.java    From candybar with Apache License 2.0 5 votes vote down vote up
public static void enqueueLoad(Context context) {
    WorkManager manager = WorkManager.getInstance(context);
    Constraints constraints = new Constraints.Builder()
            .setRequiredNetworkType(NetworkType.CONNECTED)
            .build();
    WorkRequest request = new OneTimeWorkRequest.Builder(CandyBarArtWorker.class)
            .setConstraints(constraints)
            .build();
    manager.enqueue(request);
}
 
Example #22
Source File: ComposeRepository.java    From lttrs-android with Apache License 2.0 5 votes vote down vote up
public void submitEmail(IdentityWithNameAndEmail identity, EditableEmail editableEmail) {
    final OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(SubmitEmailWorker.class)
            .setConstraints(CONNECTED_CONSTRAINT)
            .setInputData(SubmitEmailWorker.data(
                    requireAccount().id,
                    identity.getId(),
                    editableEmail.id
            ))
            .build();
    final WorkManager workManager = WorkManager.getInstance(application);
    workManager.enqueue(workRequest);
}
 
Example #23
Source File: ComposeRepository.java    From lttrs-android with Apache License 2.0 5 votes vote down vote up
public UUID saveDraft(final IdentifiableIdentity identity,
                      final ComposeViewModel.Draft draft,
                      final Collection<String> inReplyTo,
                      final EditableEmail discard) {
    final OneTimeWorkRequest saveDraftRequest = new OneTimeWorkRequest.Builder(SaveDraftWorker.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);
    WorkContinuation continuation = workManager.beginWith(saveDraftRequest);
    if (discard != null) {
        final OneTimeWorkRequest discardPreviousDraft = new OneTimeWorkRequest.Builder(DiscardDraftWorker.class)
                .setConstraints(CONNECTED_CONSTRAINT)
                .setInputData(DiscardDraftWorker.data(requireAccount().id, discard.id))
                .build();
        continuation = continuation.then(discardPreviousDraft);
    }
    continuation.enqueue();
    return saveDraftRequest.getId();
}
 
Example #24
Source File: PeriodicLocationTracker.java    From background_location_updates with Apache License 2.0 5 votes vote down vote up
public static boolean scheduleLocationTracking(int requestInterval) {
    OneTimeWorkRequest request = new OneTimeWorkRequest.Builder(PeriodicLocationTracker.class)
            .setInitialDelay(requestInterval, TimeUnit.MILLISECONDS)
            .setInputData(
                    new Data.Builder()
                            .putInt("requestInterval", requestInterval)
                            .build())
            .addTag(TRACK_IDENT)
            .build();
    WorkManager.getInstance().beginUniqueWork(TRACK_IDENT, ExistingWorkPolicy.REPLACE, request).enqueue();
    return true;
}
 
Example #25
Source File: MainActivity.java    From service with Apache License 2.0 4 votes vote down vote up
/**
 * This will create a oneshot workerA task and schedule it to run once.
 * commented out code shows how to make it recur every 24 hours.
 */
public void oneshot() {
    //for a schedule once
    OneTimeWorkRequest runWorkA = new OneTimeWorkRequest.Builder(WorkerA.class)
        .build();

    /*
    //for recur schedule, say every 24 hours, comment out above, since duplicate variables.
    PeriodicWorkRequest.Builder workerkBuilder =
        new PeriodicWorkRequest.Builder(WorkerA.class, 24,  TimeUnit.HOURS);
    // ...if you want, you can apply constraints to the builder here...
    Constraints myConstraints = new Constraints.Builder()
        //.setRequiresDeviceIdle(true)
        .setRequiresCharging(true)
        // Many other constraints are available, see the
        // Constraints.Builder reference
        .build();

   // Create the actual work object:
    PeriodicWorkRequest runWorkA = workerkBuilder.setConstraints(myConstraints)
    .build();
   */

    //now enqueue the task so it can be run.
    WorkManager.getInstance(getApplicationContext()).enqueue(runWorkA);

    //not necessary, but this will tell us the status of the task.
    LiveData<WorkInfo> status = WorkManager.getInstance(getApplicationContext()).getWorkInfoByIdLiveData(runWorkA.getId());
    status.observe(this, new Observer<WorkInfo>() {
        @Override
        public void onChanged(@Nullable WorkInfo workStatus) {
            switch (workStatus.getState()) {
                case BLOCKED:
                    tv_oneshot.setText("Status is Blocked");
                    break;
                case CANCELLED:
                    tv_oneshot.setText("Status is canceled");
                    break;
                case ENQUEUED:
                    tv_oneshot.setText("Status is enqueued");
                    break;
                case FAILED:
                    tv_oneshot.setText("Status is failed");
                    break;
                case RUNNING:
                    tv_oneshot.setText("Status is running");
                    break;
                case SUCCEEDED:
                    tv_oneshot.setText("Status is succeeded");
                    break;
                default:
                    tv_oneshot.setText("Status is unknown");
            }

        }
    });
}
 
Example #26
Source File: PhoneStateScanner.java    From PhoneProfilesPlus with Apache License 2.0 4 votes vote down vote up
static void handleEvents(/*final Context appContext*/) {
    //PPApplication.logE("PhoneStateScanner.handleEvents", "xxx");
    if (Event.getGlobalEventsRunning())
    {
        /*
        //if (DatabaseHandler.getInstance(context).getTypeEventsCount(DatabaseHandler.ETYPE_MOBILE_CELLS, false) > 0) {
            //PPApplication.logE("PhoneStateScanner.handleEvents", "start events handler");
            // start events handler
            PPApplication.logE("****** EventsHandler.handleEvents", "START run - from=PhoneStateScanner.handleEvents");

            EventsHandler eventsHandler = new EventsHandler(appContext);
            eventsHandler.handleEvents(EventsHandler.SENSOR_TYPE_PHONE_STATE);

            PPApplication.logE("****** EventsHandler.handleEvents", "END run - from=PhoneStateScanner.handleEvents");
        //}*/

        Data workData = new Data.Builder()
                .putString(PhoneProfilesService.EXTRA_DELAYED_WORK, DelayedWorksWorker.DELAYED_WORK_HANDLE_EVENTS)
                .putString(PhoneProfilesService.EXTRA_SENSOR_TYPE, EventsHandler.SENSOR_TYPE_PHONE_STATE)
                .build();

        OneTimeWorkRequest worker =
                new OneTimeWorkRequest.Builder(DelayedWorksWorker.class)
                        .addTag(DelayedWorksWorker.DELAYED_WORK_HANDLE_EVENTS_MOBILE_CELLS_SCANNER_WORK_TAG)
                        .setInputData(workData)
                        .setInitialDelay(5, TimeUnit.SECONDS)
                        .build();
        try {
            if (PPApplication.getApplicationStarted(true)) {
                WorkManager workManager = PPApplication.getWorkManagerInstance();
                if (workManager != null)
                    workManager.enqueueUniqueWork(DelayedWorksWorker.DELAYED_WORK_HANDLE_EVENTS_MOBILE_CELLS_SCANNER_WORK_TAG, ExistingWorkPolicy.KEEP, worker);
                //workManager.enqueue(worker);
            }
        } catch (Exception e) {
            PPApplication.recordException(e);
        }
    }

    /*
    // broadcast for cells editor
    Intent intent = new Intent(PPApplication.PACKAGE_NAME + ".PhoneStateChangedBroadcastReceiver_preference");
    //intent.putExtra("state", mode);
    LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
    */
}
 
Example #27
Source File: LockDeviceAfterScreenOffBroadcastReceiver.java    From PhoneProfilesPlus with Apache License 2.0 4 votes vote down vote up
@SuppressLint("NewApi")
static void setAlarm(int lockDelay, Context context)
{
    final Context appContext = context.getApplicationContext();

    if (ApplicationPreferences.applicationUseAlarmClock) {
        //Intent intent = new Intent(context, PostDelayedBroadcastReceiver.class);
        Intent intent = new Intent();
        intent.setAction(ACTION_LOCK_DEVICE_AFTER_SCREEN_OFF);
        //intent.setClass(context, PostDelayedBroadcastReceiver.class);

        PendingIntent pendingIntent = PendingIntent.getBroadcast(appContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        if (alarmManager != null) {
            Calendar now = Calendar.getInstance();
            now.add(Calendar.MILLISECOND, lockDelay);
            long alarmTime = now.getTimeInMillis();

            /*if (PPApplication.logEnabled()) {
                @SuppressLint("SimpleDateFormat")
                SimpleDateFormat sdf = new SimpleDateFormat("EE d.MM.yyyy HH:mm:ss:S");
                String result = sdf.format(alarmTime);
                PPApplication.logE("LockDeviceAfterScreenOffBroadcastReceiver.setAlarm", "alarmTime=" + result);
            }*/

            Intent editorIntent = new Intent(context, EditorProfilesActivity.class);
            editorIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            PendingIntent infoPendingIntent = PendingIntent.getActivity(context, 1000, editorIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            AlarmManager.AlarmClockInfo clockInfo = new AlarmManager.AlarmClockInfo(alarmTime + Event.EVENT_ALARM_TIME_SOFT_OFFSET, infoPendingIntent);
            alarmManager.setAlarmClock(clockInfo, pendingIntent);
        }
    }
    else {
        Data workData = new Data.Builder()
                .putString(PhoneProfilesService.EXTRA_ELAPSED_ALARMS_WORK, ElapsedAlarmsWorker.ELAPSED_ALARMS_LOCK_DEVICE_AFTER_SCREEN_OFF)
                .build();

        OneTimeWorkRequest worker =
                new OneTimeWorkRequest.Builder(ElapsedAlarmsWorker.class)
                        .addTag(ElapsedAlarmsWorker.ELAPSED_ALARMS_LOCK_DEVICE_AFTER_SCREEN_OFF_TAG_WORK)
                        .setInputData(workData)
                        .setInitialDelay(lockDelay, TimeUnit.MILLISECONDS)
                        .build();
        try {
            if (PPApplication.getApplicationStarted(true)) {
                WorkManager workManager = PPApplication.getWorkManagerInstance();
                if (workManager != null) {
                    //PPApplication.logE("[HANDLER] LockDeviceAfterScreenOffBroadcastReceiver.setAlarm", "enqueueUniqueWork - lockDelay=" + lockDelay);
                    workManager.enqueueUniqueWork(ElapsedAlarmsWorker.ELAPSED_ALARMS_LOCK_DEVICE_AFTER_SCREEN_OFF_TAG_WORK, ExistingWorkPolicy.KEEP, worker);
                }
            }
        } catch (Exception e) {
            PPApplication.recordException(e);
        }
    }

    /*final Context appContext = context.getApplicationContext();

    //Intent intent = new Intent(context, PostDelayedBroadcastReceiver.class);
    Intent intent = new Intent();
    intent.setAction(ACTION_LOCK_DEVICE_AFTER_SCREEN_OFF);
    //intent.setClass(context, PostDelayedBroadcastReceiver.class);

    PendingIntent pendingIntent = PendingIntent.getBroadcast(appContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager alarmManager = (AlarmManager) appContext.getSystemService(Context.ALARM_SERVICE);
    if (alarmManager != null) {
        if (ApplicationPreferences.applicationUseAlarmClock(context)) {

            Calendar now = Calendar.getInstance();
            now.add(Calendar.MILLISECOND, lockDelay);
            long alarmTime = now.getTimeInMillis();

            if (PPApplication.logEnabled()) {
                @SuppressLint("SimpleDateFormat")
                SimpleDateFormat sdf = new SimpleDateFormat("EE d.MM.yyyy HH:mm:ss:S");
                String result = sdf.format(alarmTime);
                PPApplication.logE("LockDeviceAfterScreenOffBroadcastReceiver.setAlarm", "alarmTime=" + result);
            }

            Intent editorIntent = new Intent(context, EditorProfilesActivity.class);
            editorIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            PendingIntent infoPendingIntent = PendingIntent.getActivity(context, 1000, editorIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            AlarmManager.AlarmClockInfo clockInfo = new AlarmManager.AlarmClockInfo(alarmTime + Event.EVENT_ALARM_TIME_SOFT_OFFSET, infoPendingIntent);
            alarmManager.setAlarmClock(clockInfo, pendingIntent);
        }
        else {
            long alarmTime = SystemClock.elapsedRealtime() + lockDelay;

            if (android.os.Build.VERSION.SDK_INT >= 23)
                alarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, alarmTime, pendingIntent);
            else //if (android.os.Build.VERSION.SDK_INT >= 19)
                alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, alarmTime, pendingIntent);
            //else
            //    alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, delayTime, pendingIntent);
        }
    }
    */
}
 
Example #28
Source File: GeofencesScannerSwitchGPSBroadcastReceiver.java    From PhoneProfilesPlus with Apache License 2.0 4 votes vote down vote up
@SuppressLint({"SimpleDateFormat", "NewApi"})
static void setAlarm(Context context)
{
    int delay = 1; // one minute with GPS ON
    if (!GeofencesScanner.useGPS)
        delay = 30;  // 30 minutes with GPS OFF

    if (ApplicationPreferences.applicationUseAlarmClock) {
        //Intent intent = new Intent(_context, GeofencesScannerSwitchGPSBroadcastReceiver.class);
        Intent intent = new Intent();
        intent.setAction(PhoneProfilesService.ACTION_GEOFENCES_SCANNER_SWITCH_GPS_BROADCAST_RECEIVER);
        //intent.setClass(context, GeofencesScannerSwitchGPSBroadcastReceiver.class);

        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        if (alarmManager != null) {
            Calendar now = Calendar.getInstance();
            now.add(Calendar.MINUTE, delay);
            long alarmTime = now.getTimeInMillis();

            /*if (PPApplication.logEnabled()) {
                SimpleDateFormat sdf = new SimpleDateFormat("EE d.MM.yyyy HH:mm:ss:S");
                String result = sdf.format(alarmTime);
                PPApplication.logE("GeofencesScannerSwitchGPSBroadcastReceiver.setAlarm", "alarmTime=" + result);
            }*/

            Intent editorIntent = new Intent(context, EditorProfilesActivity.class);
            editorIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            PendingIntent infoPendingIntent = PendingIntent.getActivity(context, 1000, editorIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            AlarmManager.AlarmClockInfo clockInfo = new AlarmManager.AlarmClockInfo(alarmTime, infoPendingIntent);
            alarmManager.setAlarmClock(clockInfo, pendingIntent);
        }
    }
    else {
        Data workData = new Data.Builder()
                .putString(PhoneProfilesService.EXTRA_ELAPSED_ALARMS_WORK, ElapsedAlarmsWorker.ELAPSED_ALARMS_GEOFENCE_SCANNER_SWITCH_GPS)
                .build();

        OneTimeWorkRequest worker =
                new OneTimeWorkRequest.Builder(ElapsedAlarmsWorker.class)
                        .addTag(ElapsedAlarmsWorker.ELAPSED_ALARMS_GEOFENCE_SCANNER_SWITCH_GPS_TAG_WORK)
                        .setInputData(workData)
                        .setInitialDelay(delay, TimeUnit.MINUTES)
                        .build();
        try {
            if (PPApplication.getApplicationStarted(true)) {
                WorkManager workManager = PPApplication.getWorkManagerInstance();
                if (workManager != null) {
                    //PPApplication.logE("[HANDLER] GeofencesScannerSwitchGPSBroadcastReceiver.setAlarm", "enqueueUniqueWork - delay="+delay);
                    workManager.enqueueUniqueWork(ElapsedAlarmsWorker.ELAPSED_ALARMS_GEOFENCE_SCANNER_SWITCH_GPS_TAG_WORK, ExistingWorkPolicy.KEEP, worker);
                }
            }
        } catch (Exception e) {
            PPApplication.recordException(e);
        }
    }

    /*
    //Intent intent = new Intent(_context, GeofencesScannerSwitchGPSBroadcastReceiver.class);
    Intent intent = new Intent();
    intent.setAction(PhoneProfilesService.ACTION_GEOFENCES_SCANNER_SWITCH_GPS_BROADCAST_RECEIVER);
    //intent.setClass(context, GeofencesScannerSwitchGPSBroadcastReceiver.class);

    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    if (alarmManager != null) {
        if (ApplicationPreferences.applicationUseAlarmClock(context)) {

            Calendar now = Calendar.getInstance();
            now.add(Calendar.MINUTE, delay);
            long alarmTime = now.getTimeInMillis();

            if (PPApplication.logEnabled()) {
                SimpleDateFormat sdf = new SimpleDateFormat("EE d.MM.yyyy HH:mm:ss:S");
                String result = sdf.format(alarmTime);
                PPApplication.logE("GeofencesScannerSwitchGPSBroadcastReceiver.setAlarm", "alarmTime=" + result);
            }

            Intent editorIntent = new Intent(context, EditorProfilesActivity.class);
            editorIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            PendingIntent infoPendingIntent = PendingIntent.getActivity(context, 1000, editorIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            AlarmManager.AlarmClockInfo clockInfo = new AlarmManager.AlarmClockInfo(alarmTime, infoPendingIntent);
            alarmManager.setAlarmClock(clockInfo, pendingIntent);
        }
        else {
            long alarmTime = SystemClock.elapsedRealtime() + delay * 60 * 1000;

            if (android.os.Build.VERSION.SDK_INT >= 23)
                alarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, alarmTime, pendingIntent);
            else //if (android.os.Build.VERSION.SDK_INT >= 19)
                alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, alarmTime, pendingIntent);
            //else
            //    alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, alarmTime, pendingIntent);
        }
    }
    */
}
 
Example #29
Source File: LockDeviceActivityFinishBroadcastReceiver.java    From PhoneProfilesPlus with Apache License 2.0 4 votes vote down vote up
@SuppressLint({"SimpleDateFormat", "NewApi"})
static void setAlarm(Context context)
{
    removeAlarm(context);

    int delay = 20; // 20 seconds

    if (ApplicationPreferences.applicationUseAlarmClock) {
        //Intent intent = new Intent(_context, LockDeviceActivityFinishBroadcastReceiver.class);
        Intent intent = new Intent();
        intent.setAction(PhoneProfilesService.ACTION_LOCK_DEVICE_ACTIVITY_FINISH_BROADCAST_RECEIVER);
        //intent.setClass(context, LockDeviceActivityFinishBroadcastReceiver.class);

        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        if (alarmManager != null) {
            Calendar now = Calendar.getInstance();
            now.add(Calendar.SECOND, delay);
            long alarmTime = now.getTimeInMillis();

            /*if (PPApplication.logEnabled()) {
                SimpleDateFormat sdf = new SimpleDateFormat("EE d.MM.yyyy HH:mm:ss:S");
                String result = sdf.format(alarmTime);
                PPApplication.logE("[HANDLER] LockDeviceActivityFinishBroadcastReceiver.setAlarm", "alarmTime=" + result);
            }*/

            Intent editorIntent = new Intent(context, EditorProfilesActivity.class);
            editorIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            PendingIntent infoPendingIntent = PendingIntent.getActivity(context, 1000, editorIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            AlarmManager.AlarmClockInfo clockInfo = new AlarmManager.AlarmClockInfo(alarmTime, infoPendingIntent);
            alarmManager.setAlarmClock(clockInfo, pendingIntent);
        }
    }
    else {
        Data workData = new Data.Builder()
                .putString(PhoneProfilesService.EXTRA_ELAPSED_ALARMS_WORK, ElapsedAlarmsWorker.ELAPSED_ALARMS_LOCK_DEVICE_FINISH_ACTIVITY)
                .build();

        OneTimeWorkRequest worker =
                new OneTimeWorkRequest.Builder(ElapsedAlarmsWorker.class)
                        .addTag(ElapsedAlarmsWorker.ELAPSED_ALARMS_LOCK_DEVICE_FINISH_ACTIVITY_TAG_WORK)
                        .setInputData(workData)
                        .setInitialDelay(delay, TimeUnit.SECONDS)
                        .build();
        try {
            if (PPApplication.getApplicationStarted(true)) {
                WorkManager workManager = PPApplication.getWorkManagerInstance();
                if (workManager != null) {
                    //PPApplication.logE("[HANDLER] LockDeviceActivityFinishBroadcastReceiver.setAlarm", "enqueueUniqueWork - alarmTime=" + delay);
                    workManager.enqueueUniqueWork(ElapsedAlarmsWorker.ELAPSED_ALARMS_LOCK_DEVICE_FINISH_ACTIVITY_TAG_WORK, ExistingWorkPolicy.KEEP, worker);
                }
            }
        } catch (Exception e) {
            PPApplication.recordException(e);
        }
    }

    /*//Intent intent = new Intent(_context, LockDeviceActivityFinishBroadcastReceiver.class);
    Intent intent = new Intent();
    intent.setAction(PhoneProfilesService.ACTION_LOCK_DEVICE_ACTIVITY_FINISH_BROADCAST_RECEIVER);
    //intent.setClass(context, LockDeviceActivityFinishBroadcastReceiver.class);

    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    if (alarmManager != null) {
        if (ApplicationPreferences.applicationUseAlarmClock(context)) {

            Calendar now = Calendar.getInstance();
            now.add(Calendar.SECOND, delay);
            long alarmTime = now.getTimeInMillis();

            if (PPApplication.logEnabled()) {
                SimpleDateFormat sdf = new SimpleDateFormat("EE d.MM.yyyy HH:mm:ss:S");
                String result = sdf.format(alarmTime);
                PPApplication.logE("LockDeviceActivityFinishBroadcastReceiver.setAlarm", "alarmTime=" + result);
            }

            Intent editorIntent = new Intent(context, EditorProfilesActivity.class);
            editorIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            PendingIntent infoPendingIntent = PendingIntent.getActivity(context, 1000, editorIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            AlarmManager.AlarmClockInfo clockInfo = new AlarmManager.AlarmClockInfo(alarmTime, infoPendingIntent);
            alarmManager.setAlarmClock(clockInfo, pendingIntent);
        }
        else {
            long alarmTime = SystemClock.elapsedRealtime() + delay * 1000;

            if (android.os.Build.VERSION.SDK_INT >= 23)
                alarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, alarmTime, pendingIntent);
            else //if (android.os.Build.VERSION.SDK_INT >= 19)
                alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, alarmTime, pendingIntent);
            //else
            //    alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, alarmTime, pendingIntent);
        }
    }
    */
}
 
Example #30
Source File: TwilightScanner.java    From PhoneProfilesPlus with Apache License 2.0 4 votes vote down vote up
private void setTwilightState(TwilightState state) {
    synchronized (mLock) {
        if ((mTwilightState == null) || (state == null) || !mTwilightState.equals(state)) {
            //PPApplication.logE("TwilightScanner.setTwilightState", "Twilight state changed: " + state);

            mTwilightState = state;

            //final Context appContext = context.getApplicationContext();

            if (!PPApplication.getApplicationStarted(true))
                // application is not started
                return;

            if (Event.getGlobalEventsRunning()) {
                //PPApplication.logE("TwilightScanner.setTwilightState", "xxx");

                Data workData = new Data.Builder()
                        .putString(PhoneProfilesService.EXTRA_DELAYED_WORK, DelayedWorksWorker.DELAYED_WORK_HANDLE_EVENTS)
                        .putString(PhoneProfilesService.EXTRA_SENSOR_TYPE, EventsHandler.SENSOR_TYPE_TIME)
                        .build();

                OneTimeWorkRequest worker =
                        new OneTimeWorkRequest.Builder(DelayedWorksWorker.class)
                                .addTag(DelayedWorksWorker.DELAYED_WORK_HANDLE_EVENTS_TWILIGHT_SCANNER_WORK_TAG)
                                .setInputData(workData)
                                .setInitialDelay(10, TimeUnit.SECONDS) // 10 seconds to get location
                                .build();
                try {
                    if (PPApplication.getApplicationStarted(true)) {
                        WorkManager workManager = PPApplication.getWorkManagerInstance();
                        if (workManager != null)
                            workManager.enqueueUniqueWork(DelayedWorksWorker.DELAYED_WORK_HANDLE_EVENTS_TWILIGHT_SCANNER_WORK_TAG, ExistingWorkPolicy.KEEP, worker);
                        //workManager.enqueue(worker);
                    }
                } catch (Exception e) {
                    PPApplication.recordException(e);
                }

                /*
                PPApplication.startHandlerThread();//"TwilightScanner.setTwilightState"
                final Handler handler = new Handler(PPApplication.handlerThread.getLooper());
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        PowerManager powerManager = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
                        PowerManager.WakeLock wakeLock = null;
                        try {
                            if (powerManager != null) {
                                wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, PPApplication.PACKAGE_NAME + ":TwilightScanner_setTwilightState");
                                wakeLock.acquire(10 * 60 * 1000);
                            }

                            PPApplication.logE("****** EventsHandler.handleEvents", "START run - from=TwilightScanner.setTwilightState");

                            EventsHandler eventsHandler = new EventsHandler(appContext);
                            eventsHandler.handleEvents(EventsHandler.SENSOR_TYPE_TIME);

                            PPApplication.logE("****** EventsHandler.handleEvents", "END run - from=TwilightScanner.setTwilightState");
                        } finally {
                            if ((wakeLock != null) && wakeLock.isHeld()) {
                                try {
                                    wakeLock.release();
                                } catch (Exception ignored) {
                                }
                            }
                        }
                    }
                });
                */
            }
        }
    }
}