androidx.work.ExistingWorkPolicy Java Examples
The following examples show how to use
androidx.work.ExistingWorkPolicy.
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: LttrsRepository.java From lttrs-android with Apache License 2.0 | 6 votes |
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 #2
Source File: AvoidRescheduleReceiverWorker.java From PhoneProfilesPlus with Apache License 2.0 | 6 votes |
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: WorkerHelper.java From GeometricWeather with GNU Lesser General Public License v3.0 | 6 votes |
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 #4
Source File: WorkerHelper.java From GeometricWeather with GNU Lesser General Public License v3.0 | 6 votes |
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 #5
Source File: DynamicTheme.java From dynamic-support with Apache License 2.0 | 6 votes |
/** * 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 #6
Source File: WorkerFts.java From FairEmail with GNU General Public License v3.0 | 6 votes |
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 #7
Source File: LttrsRepository.java From lttrs-android with Apache License 2.0 | 6 votes |
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 #8
Source File: LttrsRepository.java From lttrs-android with Apache License 2.0 | 6 votes |
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 #9
Source File: LttrsRepository.java From lttrs-android with Apache License 2.0 | 6 votes |
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 #10
Source File: LttrsRepository.java From lttrs-android with Apache License 2.0 | 6 votes |
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 #11
Source File: LttrsRepository.java From lttrs-android with Apache License 2.0 | 6 votes |
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 #12
Source File: SyncManagerPresenter.java From dhis2-android-capture-app with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Override public void syncData() { view.syncData(); analyticsHelper.setEvent(SYNC_DATA_NOW, CLICK, SYNC_DATA_NOW); WorkerItem workerItem = new WorkerItem(Constants.DATA_NOW, WorkerType.DATA, null, null, ExistingWorkPolicy.KEEP, null); workManagerController.syncDataForWorker(workerItem); checkData(); }
Example #13
Source File: SyncManagerPresenter.java From dhis2-android-capture-app with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Override public void syncMeta() { view.syncMeta(); analyticsHelper.setEvent(SYNC_METADATA_NOW, CLICK, SYNC_METADATA_NOW); WorkerItem workerItem = new WorkerItem(Constants.META_NOW, WorkerType.METADATA, null, null, ExistingWorkPolicy.KEEP, null); workManagerController.syncDataForWorker(workerItem); }
Example #14
Source File: DataSyncWorkManager.java From ground-android with Apache License 2.0 | 5 votes |
private void enqueueSyncWorkerInternal(String featureId) { // Rather than having running workers monitor the queue for new mutations for their respective // featureId, we instead queue a new worker on each new mutation. This simplifies the worker // implementation and avoids race conditions in the rare event the worker finishes just when new // mutations are added to the db. getWorkManager() .enqueueUniqueWork( LocalMutationSyncWorker.class.getName(), ExistingWorkPolicy.APPEND, buildWorkerRequest(featureId)); }
Example #15
Source File: PeriodicLocationTracker.java From background_location_updates with Apache License 2.0 | 5 votes |
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 #16
Source File: GeofencesScannerSwitchGPSBroadcastReceiver.java From PhoneProfilesPlus with Apache License 2.0 | 4 votes |
@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 #17
Source File: WorkManagerUtils.java From cathode with Apache License 2.0 | 4 votes |
public static void enqueueUniqueNow(WorkManager workManager, String tag, Class<? extends ListenableWorker> workerClass) { WorkmanagerKt.enqueueUniqueNow(workManager, tag, workerClass, ExistingWorkPolicy.APPEND, null, true); }
Example #18
Source File: PhoneStateScanner.java From PhoneProfilesPlus with Apache License 2.0 | 4 votes |
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 #19
Source File: DataWrapper.java From PhoneProfilesPlus with Apache License 2.0 | 4 votes |
@SuppressLint("NewApi") // delay is in seconds, max 5 void restartEventsWithDelay(int delay, boolean alsoRescan, final boolean unblockEventsRun, /*final boolean reactivateProfile,*/ /*boolean clearOld,*/ final int logType) { //PPApplication.logE("[TEST BATTERY] DataWrapper.restartEventsWithDelay","xxx"); //"clearOld="+clearOld); /*if (PhoneProfilesService.getInstance() != null) PhoneProfilesService.getInstance().willBeDoRestartEvents = true;*/ //final DataWrapper dataWrapper = copyDataWrapper(); /*if (PhoneProfilesService.getInstance() != null) { ++PhoneProfilesService.getInstance().willBeDoRestartEvents; }*/ /* if (clearOld) { Data workData = new Data.Builder() .putBoolean(PhoneProfilesService.EXTRA_UNBLOCK_EVENTS_RUN, unblockEventsRun) .putInt(PhoneProfilesService.EXTRA_LOG_TYPE, logType) .build(); OneTimeWorkRequest restartEventsWithDelayWorker = new OneTimeWorkRequest.Builder(RestartEventsWithDelayWorker.class) .setInputData(workData) .setInitialDelay(delay, TimeUnit.SECONDS) .build(); try { WorkManager workManager = WorkManager.getInstance(context); // workManager.cancelUniqueWork("restartEventsWithDelayClearOldWork"); // workManager.cancelAllWorkByTag("restartEventsWithDelayClearOldWork"); // workManager.cancelUniqueWork("restartEventsWithDelayNotClearOldWork"); // workManager.cancelAllWorkByTag("restartEventsWithDelayNotClearOldWork"); workManager.enqueueUniqueWork("restartEventsWithDelayClearOldWork", ExistingWorkPolicy.KEEP, restartEventsWithDelayWorker); } catch (Exception ignored) {} // PPApplication.startHandlerThreadRestartEventsWithDelay(); // PPApplication.restartEventsWithDelayHandler.removeCallbacksAndMessages(null); // PPApplication.restartEventsWithDelayHandler.postDelayed(new Runnable() { // @Override // public void run() { // PPApplication.logE("[TEST HANDLER] DataWrapper.restartEventsWithDelay", "restart from handler"); // if (logType != ALTYPE_UNDEFINED) // dataWrapper.addActivityLog(logType, null, null, null, 0); // dataWrapper.restartEventsWithRescan(unblockEventsRun, false, true, false); // } // }, delay * 1000); //PostDelayedBroadcastReceiver.setAlarmForRestartEvents(delay, true, unblockEventsRun, logType, context); } else {*/ Data workData = new Data.Builder() .putBoolean(PhoneProfilesService.EXTRA_ALSO_RESCAN, alsoRescan) .putBoolean(PhoneProfilesService.EXTRA_UNBLOCK_EVENTS_RUN, unblockEventsRun) .putInt(PhoneProfilesService.EXTRA_LOG_TYPE, logType) .build(); OneTimeWorkRequest restartEventsWithDelayWorker = new OneTimeWorkRequest.Builder(RestartEventsWithDelayWorker.class) .addTag(RestartEventsWithDelayWorker.WORK_TAG) .setInputData(workData) .setInitialDelay(delay, TimeUnit.SECONDS) .build(); try { if (PPApplication.getApplicationStarted(true)) { WorkManager workManager = PPApplication.getWorkManagerInstance(); if (workManager != null) { //workManager.enqueueUniqueWork("restartEventsWithDelayNotClearOldWork", ExistingWorkPolicy.KEEP, restartEventsWithDelayWorker); workManager.enqueueUniqueWork(RestartEventsWithDelayWorker.WORK_TAG, ExistingWorkPolicy.KEEP, restartEventsWithDelayWorker); } } } catch (Exception e) { PPApplication.recordException(e); } /*PPApplication.startHandlerThread("DataWrapper.restartEventsWithDelay"); final Handler handler = new Handler(PPApplication.handlerThread.getLooper()); handler.postDelayed(new Runnable() { @Override public void run() { PPApplication.logE("[TEST HANDLER] DataWrapper.restartEventsWithDelay", "restart from handler"); if (logType != ALTYPE_UNDEFINED) dataWrapper.addActivityLog(logType, null, null, null, 0); dataWrapper.restartEventsWithRescan(unblockEventsRun, false, true, false); } }, delay * 1000);*/ //PostDelayedBroadcastReceiver.setAlarmForRestartEvents(delay, false, unblockEventsRun, /*reactivateProfile,*/ logType, context); //} }
Example #20
Source File: BluetoothScanWorker.java From PhoneProfilesPlus with Apache License 2.0 | 4 votes |
static void finishCLScan(final Context context) { synchronized (PPApplication.bluetoothScanMutex) { //PPApplication.logE("BluetoothScanWorker.finishCLScan", "BluetoothScanBroadcastReceiver: discoveryStarted=" + WifiBluetoothScanner.bluetoothDiscoveryStarted); if (BluetoothScanner.bluetoothDiscoveryStarted) { BluetoothScanner.bluetoothDiscoveryStarted = false; List<BluetoothDeviceData> scanResults = new ArrayList<>(); if (BluetoothScanner.tmpBluetoothScanResults != null) { //PPApplication.logE("BluetoothScanWorker.finishCLScan", "WifiBluetoothScanner.tmpBluetoothScanResults.size="+WifiBluetoothScanner.tmpBluetoothScanResults.size()); for (BluetoothDeviceData device : BluetoothScanner.tmpBluetoothScanResults) { scanResults.add(new BluetoothDeviceData(device.getName(), device.address, device.type, false, 0, false, true)); //PPApplication.logE("BluetoothScanWorker.finishCLScan", "device="+device.getName()); } } //else // PPApplication.logE("BluetoothScanWorker.finishCLScan", "tmpBluetoothScanResults=null"); saveCLScanResults(context, scanResults); setWaitForResults(context, false); int forceOneScan = ApplicationPreferences.prefForceOneBluetoothScan; BluetoothScanner.setForceOneBluetoothScan(context, BluetoothScanner.FORCE_ONE_SCAN_DISABLED); if (forceOneScan != BluetoothScanner.FORCE_ONE_SCAN_FROM_PREF_DIALOG)// not start service for force scan { Data workData = new Data.Builder() .putString(PhoneProfilesService.EXTRA_DELAYED_WORK, DelayedWorksWorker.DELAYED_WORK_HANDLE_EVENTS) .putString(PhoneProfilesService.EXTRA_SENSOR_TYPE, EventsHandler.SENSOR_TYPE_BLUETOOTH_SCANNER) .build(); OneTimeWorkRequest worker = new OneTimeWorkRequest.Builder(DelayedWorksWorker.class) .addTag(DelayedWorksWorker.DELAYED_WORK_HANDLE_EVENTS_BLUETOOTH_CE_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_BLUETOOTH_CE_SCANNER_WORK_TAG, ExistingWorkPolicy.KEEP, worker); //workManager.enqueue(worker); } } catch (Exception e) { PPApplication.recordException(e); } /*PPApplication.startHandlerThread("BluetoothScanWorker.finishCLScan"); final Handler handler = new Handler(PPApplication.handlerThread.getLooper()); handler.postDelayed(new Runnable() { @Override public void run() { PowerManager powerManager = (PowerManager) context.getSystemService(POWER_SERVICE); PowerManager.WakeLock wakeLock = null; try { if (powerManager != null) { wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, PPApplication.PACKAGE_NAME + ":BluetoothScanWorker_finishCLScan"); wakeLock.acquire(10 * 60 * 1000); } // start events handler EventsHandler eventsHandler = new EventsHandler(context); eventsHandler.handleEvents(EventsHandler.SENSOR_TYPE_BLUETOOTH_SCANNER); } finally { if ((wakeLock != null) && wakeLock.isHeld()) { try { wakeLock.release(); } catch (Exception ignored) {} } } } }, 5000);*/ //PostDelayedBroadcastReceiver.setAlarmForHandleEvents(EventsHandler.SENSOR_TYPE_BLUETOOTH_SCANNER, 5, context); } BluetoothScanner.tmpBluetoothScanResults = null; } } }
Example #21
Source File: LocationGeofenceEditorActivity.java From PhoneProfilesPlus with Apache License 2.0 | 4 votes |
private void startIntentService(boolean updateName) { /*Intent intent = new Intent(this, FetchAddressIntentService.class); intent.putExtra(RECEIVER, mResultReceiver); intent.putExtra(LOCATION_DATA_EXTRA, mLocation); intent.putExtra(UPDATE_NAME_EXTRA, updateName); startService(intent);*/ Data workData = new Data.Builder() .putDouble(LATITUDE_EXTRA, mLocation.getLatitude()) .putDouble(LONGITUDE_EXTRA, mLocation.getLongitude()) .putBoolean(UPDATE_NAME_EXTRA, updateName) .build(); OneTimeWorkRequest fetchAddressWorker = new OneTimeWorkRequest.Builder(FetchAddressWorker.class) .addTag(LocationGeofenceEditorActivity.FETCH_ADDRESS_WORK_TAG) .setInputData(workData) .build(); try { if (PPApplication.getApplicationStarted(true)) { WorkManager workManager = PPApplication.getWorkManagerInstance(); if (workManager != null) { workManager.enqueueUniqueWork(LocationGeofenceEditorActivity.FETCH_ADDRESS_WORK_TAG, ExistingWorkPolicy.KEEP, fetchAddressWorker); workManager.getWorkInfoByIdLiveData(fetchAddressWorker.getId()) .observe(this, new Observer<WorkInfo>() { @Override public void onChanged(@Nullable WorkInfo workInfo) { //PPApplication.logE("LocationGeofenceEditorActivity.getWorkInfoByIdLiveData", "xxx"); if ((workInfo != null) && (workInfo.getState() == WorkInfo.State.SUCCEEDED)) { //PPApplication.logE("LocationGeofenceEditorActivity.getWorkInfoByIdLiveData", "WorkInfo.State.SUCCEEDED"); Data outputData = workInfo.getOutputData(); //PPApplication.logE("LocationGeofenceEditorActivity.getWorkInfoByIdLiveData", "outputData=" + outputData); int resultCode = outputData.getInt(RESULT_CODE, FAILURE_RESULT); //PPApplication.logE("LocationGeofenceEditorActivity.getWorkInfoByIdLiveData", "resultCode=" + resultCode); boolean enableAddressButton = false; if (resultCode == SUCCESS_RESULT) { //PPApplication.logE("LocationGeofenceEditorActivity.getWorkInfoByIdLiveData", "resultCode=" + resultCode); // Display the address string // or an error message sent from the intent service. String addressOutput = outputData.getString(RESULT_DATA_KEY); //PPApplication.logE("LocationGeofenceEditorActivity.getWorkInfoByIdLiveData", "addressOutput=" + addressOutput); addressText.setText(addressOutput); if (outputData.getBoolean(UPDATE_NAME_EXTRA, false)) geofenceNameEditText.setText(addressOutput); updateEditedMarker(false); enableAddressButton = true; } GlobalGUIRoutines.setImageButtonEnabled(enableAddressButton, addressButton, getApplicationContext()); } } }); } } } catch (Exception e) { //Log.e("LocationGeofenceEditorActivity.startIntentService", Log.getStackTraceString(e)); PPApplication.recordException(e); } }
Example #22
Source File: TwilightScanner.java From PhoneProfilesPlus with Apache License 2.0 | 4 votes |
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) { } } } } }); */ } } } }
Example #23
Source File: LockDeviceActivityFinishBroadcastReceiver.java From PhoneProfilesPlus with Apache License 2.0 | 4 votes |
@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 #24
Source File: LockDeviceAfterScreenOffBroadcastReceiver.java From PhoneProfilesPlus with Apache License 2.0 | 4 votes |
@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 #25
Source File: CommCareApplication.java From commcare-android with Apache License 2.0 | 2 votes |
private void purgeLogs() { if (shouldRunLogDeletion()) { OneTimeWorkRequest deleteLogsRequest = new OneTimeWorkRequest.Builder(DeleteLogs.class).build(); WorkManager.getInstance(CommCareApplication.instance()) .enqueueUniqueWork(DELETE_LOGS_REQUEST, ExistingWorkPolicy.KEEP, deleteLogsRequest); } }
Example #26
Source File: PixelWatchFace.java From PixelWatchFace with GNU General Public License v3.0 | 1 votes |
private void initWeatherUpdater(boolean forceUpdate) { String TAG = "initWeatherUpdater"; if (!mSettings.isWeatherDisabled()) { if (ActivityCompat .checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { Log.d(TAG, "requesting permission"); requestPermissions(); } else { Log.d(TAG, "last weather retrieved: " + mCurrentWeather.getTime()); Log.d(TAG, "current time: " + System.currentTimeMillis()); Constraints constraints = new Constraints.Builder() .setRequiredNetworkType(NetworkType.CONNECTED) .build(); if (forceUpdate || mWeatherRequestedTime == 0 || System.currentTimeMillis() - mWeatherRequestedTime >= TimeUnit.MINUTES .toMillis(WEATHER_UPDATE_INTERVAL)) { OneTimeWorkRequest locationUpdate = new OneTimeWorkRequest.Builder(LocationUpdateWorker.class) .setConstraints(constraints) // forced weather update is expected to happen sooner, so // try again in (30 seconds * attempt count). After 3 failed // attempts, it would wait 1.5 minutes before retrying again .setBackoffCriteria(BackoffPolicy.LINEAR, WEATHER_BACKOFF_DELAY_ONETIME, TimeUnit.SECONDS) .build(); OneTimeWorkRequest weatherUpdate = new OneTimeWorkRequest.Builder(WeatherUpdateWorker.class) .setConstraints(constraints) .setBackoffCriteria(BackoffPolicy.LINEAR, WEATHER_BACKOFF_DELAY_ONETIME, TimeUnit.SECONDS) .build(); WorkManager.getInstance(getApplicationContext()) .beginUniqueWork(WEATHER_UPDATE_WORKER, ExistingWorkPolicy.REPLACE, locationUpdate) .then(weatherUpdate) .enqueue(); mWeatherRequestedTime = System.currentTimeMillis(); Observer<WorkInfo> weatherObserver = new Observer<WorkInfo>() { @Override public void onChanged(WorkInfo workInfo) { if (workInfo != null) { Log.d(TAG, "weatherObserver onChanged : " + workInfo.toString()); if (workInfo.getState().isFinished()) { String currentWeatherJSON = workInfo.getOutputData() .getString(KEY_WEATHER_JSON); Log.d(TAG, "outputWeather: " + currentWeatherJSON); Weather newCurrentWeather = new Gson() .fromJson(currentWeatherJSON, Weather.class); // check if newCurrentWeather is actually valid if (newCurrentWeather != null && newCurrentWeather.getTemperature() != NO_TEMPERATURE) { // copy bitmap over so we don't have to regenerate it if (newCurrentWeather.getIconID() == mCurrentWeather.getIconID()) { newCurrentWeather .setIconBitmap(mCurrentWeather.getIconBitmap(getApplicationContext())); } mCurrentWeather = newCurrentWeather; invalidate(); // redraw to update the displayed weather } } } } }; WatchFaceUtil.observeUntilFinished(WorkManager.getInstance(getApplicationContext()) .getWorkInfoByIdLiveData(weatherUpdate.getId()), weatherObserver); } } } }