androidx.work.Data Java Examples

The following examples show how to use androidx.work.Data. 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: 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 #2
Source File: WorkerParameters.java    From service with Apache License 2.0 6 votes vote down vote up
@NonNull
@Override
public Result doWork() {

    //we are pretending this is some complex work to be done.   instead of a random number.
    r = new Random();
    // Fetch the arguments (and specify default values):
    int x = getInputData().getInt(KEY_X_ARG, 0);

    int result = r.nextInt(x);


    //...set the output, and we're done!
    Data output = new Data.Builder()
        .putInt(KEY_RESULT, result)
        .build();

    return Result.success(output);
}
 
Example #3
Source File: UpdateActivity.java    From commcare-android with Apache License 2.0 6 votes vote down vote up
private void connectToUpdateWorker() {
    WorkManager.getInstance(getApplicationContext())
            .getWorkInfosForUniqueWorkLiveData(UpdateHelper.getUpdateRequestName())
            .observe(this, listOfWorkInfo -> {

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

                WorkInfo updateInfo = listOfWorkInfo.get(0);
                boolean running = updateInfo.getState() == WorkInfo.State.RUNNING;
                if (running) {
                    Data data = updateInfo.getProgress();
                    publishUpdateProgress(data.getInt(UpdateWorker.Progress_Complete, -1),
                            data.getInt(UpdateWorker.Progress_Total, -1));
                } else {
                    // Worker getting fired when not running imply completion of worker
                    ResultAndError<AppInstallStatus> lastUpdateResult = getlastStageUpdateResult();
                    if (lastUpdateResult != null) {
                        handleTaskCompletion(getlastStageUpdateResult());
                    }
                }
            });
}
 
Example #4
Source File: ThreadViewModel.java    From lttrs-android with Apache License 2.0 6 votes vote down vote up
public void waitForEdit(UUID uuid) {
    final WorkManager workManager = WorkManager.getInstance(getApplication());
    LiveData<WorkInfo> liveData = workManager.getWorkInfoByIdLiveData(uuid);
    liveData.observeForever(new Observer<WorkInfo>() {
        @Override
        public void onChanged(WorkInfo workInfo) {
            if (workInfo.getState() == WorkInfo.State.SUCCEEDED) {
                final Data data = workInfo.getOutputData();
                final String threadId = data.getString("threadId");
                if (threadId != null && !ThreadViewModel.this.threadId.equals(threadId)) {
                    LOGGER.info("redirecting to thread {}", threadId);
                    threadViewRedirect.postValue(new Event<>(threadId));
                }
                liveData.removeObserver(this);
            } else if (workInfo.getState() == WorkInfo.State.FAILED) {
                liveData.removeObserver(this);
            }
        }
    });
}
 
Example #5
Source File: AutomaticBackup.java    From trackworktime with GNU General Public License v3.0 6 votes vote down vote up
@NonNull
@Override
public Result doWork() {
    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        return Result.failure(new Data.Builder().putString("error", "the app doesn't have the permission to write to external storage - please trigger a manual backup to grant this permission").build());
    }
    final File externalStorageDirectory = Environment.getExternalStorageDirectory();
    if (externalStorageDirectory == null) {
        Logger.warn("automatic backup failed because getExternalStorageDirectory() returned null");
        return Result.failure(new Data.Builder().putString("error", "external storage directory could not be found").build());
    }
    final File backupDir = new File(externalStorageDirectory, Constants.DATA_DIR);
    final File backupFile = new File(backupDir, AUTOMATIC_BACKUP_FILE);

    Logger.info("starting automatic backup");
    BackupUtil.doBackup(context, backupFile);
    return Result.success();
}
 
Example #6
Source File: AbstractCreateEmailWorker.java    From lttrs-android with Apache License 2.0 6 votes vote down vote up
public static Data data(final Long account,
                        final String identity,
                        final Collection<String> inReplyTo,
                        final Collection<EmailAddress> to,
                        final Collection<EmailAddress> cc,
                        final String subject,
                        final String body) {
    return new Data.Builder()
            .putLong(ACCOUNT_KEY, account)
            .putString(IDENTITY_KEY, identity)
            .putStringArray(IN_REPLY_TO_KEY, inReplyTo.toArray(new String[0]))
            .putString(TO_KEY, EmailAddressUtil.toHeaderValue(to))
            .putString(CC_KEY, EmailAddressUtil.toHeaderValue(cc))
            .putString(SUBJECT_KEY, subject)
            .putString(BODY_KEY, body)
            .build();
}
 
Example #7
Source File: AbstractMuaWorker.java    From lttrs-android with Apache License 2.0 5 votes vote down vote up
AbstractMuaWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
    super(context, workerParams);
    final Data data = getInputData();
    if (data.hasKeyWithValueOfType(ACCOUNT_KEY, Long.class)) {
        this.account = data.getLong(ACCOUNT_KEY, 0L);
    } else {
        throw new IllegalStateException("Missing required account");
    }
}
 
Example #8
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 #9
Source File: UploadWorker.java    From flutter_uploader with MIT License 5 votes vote down vote up
private Data createOutputErrorData(
    int status, int statusCode, String code, String message, String[] details) {
  return new Data.Builder()
      .putInt(UploadWorker.EXTRA_STATUS_CODE, statusCode)
      .putInt(UploadWorker.EXTRA_STATUS, status)
      .putString(UploadWorker.EXTRA_ERROR_CODE, code)
      .putString(UploadWorker.EXTRA_ERROR_MESSAGE, message)
      .putStringArray(UploadWorker.EXTRA_ERROR_DETAILS, details)
      .build();
}
 
Example #10
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 #11
Source File: FetchAddressWorker.java    From PhoneProfilesPlus with Apache License 2.0 5 votes vote down vote up
private Data generateResult(int resultCode, String message, boolean updateName) {
    // Create the output of the work
    /*if (PPApplication.logEnabled()) {
        PPApplication.logE("FetchAddressWorker.generateResult", "resultCode=" + resultCode);
        PPApplication.logE("FetchAddressWorker.generateResult", "message=" + message);
        PPApplication.logE("FetchAddressWorker.generateResult", "updateName=" + updateName);
    }*/

    return new Data.Builder()
            .putInt(LocationGeofenceEditorActivity.RESULT_CODE, resultCode)
            .putString(LocationGeofenceEditorActivity.RESULT_DATA_KEY, message)
            .putBoolean(LocationGeofenceEditorActivity.UPDATE_NAME_EXTRA, updateName)
            .build();
}
 
Example #12
Source File: AbstractCreateEmailWorker.java    From lttrs-android with Apache License 2.0 5 votes vote down vote up
AbstractCreateEmailWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
    super(context, workerParams);
    final Data data = workerParams.getInputData();
    this.identity = data.getString(IDENTITY_KEY);
    final String to = data.getString(TO_KEY);
    this.to = to == null ? Collections.emptyList() : EmailAddressUtil.parse(to);
    final String cc = data.getString(CC_KEY);
    this.cc = cc == null ? Collections.emptyList() : EmailAddressUtil.parse(cc);
    this.subject = data.getString(SUBJECT_KEY);
    this.body = data.getString(BODY_KEY);
    final String[] inReplyTo = data.getStringArray(IN_REPLY_TO_KEY);
    this.inReplyTo = inReplyTo == null ? Collections.emptyList() : Arrays.asList(inReplyTo);
}
 
Example #13
Source File: SubmitEmailWorker.java    From lttrs-android with Apache License 2.0 5 votes vote down vote up
public static Data data(Long account, String identity, String emailId) {
    return new Data.Builder()
            .putLong(ACCOUNT_KEY, account)
            .putString(IDENTITY_KEY, identity)
            .putString(EMAIL_ID, emailId)
            .build();
}
 
Example #14
Source File: ModifyKeywordWorker.java    From lttrs-android with Apache License 2.0 5 votes vote down vote up
public static Data data(final Long account, final String threadId, final String keyword, final boolean targetState) {
    return new Data.Builder()
            .putLong(ACCOUNT_KEY, account)
            .putString(THREAD_ID_KEY, threadId)
            .putString(KEYWORD_KEY, keyword)
            .putBoolean(TARGET_STATE_KEY, targetState)
            .build();
}
 
Example #15
Source File: ModifyKeywordWorker.java    From lttrs-android with Apache License 2.0 5 votes vote down vote up
public ModifyKeywordWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
    super(context, workerParams);
    final Data data = getInputData();
    this.threadId = data.getString(THREAD_ID_KEY);
    this.keyword = data.getString(KEYWORD_KEY);
    this.target = data.getBoolean(TARGET_STATE_KEY, false);
}
 
Example #16
Source File: CopyToMailboxWorker.java    From lttrs-android with Apache License 2.0 5 votes vote down vote up
public static Data data(Long account, String threadId, IdentifiableMailboxWithRole mailbox) {
    return new Data.Builder()
            .putLong(ACCOUNT_KEY, account)
            .putString(THREAD_ID_KEY, threadId)
            .putString(MAILBOX_ID_KEY, mailbox.getId())
            .build();
}
 
Example #17
Source File: RemoveFromMailboxWorker.java    From lttrs-android with Apache License 2.0 5 votes vote down vote up
public static Data data(Long account, String threadId, IdentifiableMailboxWithRole mailbox) {
    return new Data.Builder()
            .putLong(ACCOUNT_KEY, account)
            .putString(THREAD_ID_KEY, threadId)
            .putString(MAILBOX_ID_KEY, mailbox.getId())
            .build();
}
 
Example #18
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 #19
Source File: DataWrapper.java    From PhoneProfilesPlus with Apache License 2.0 4 votes vote down vote up
@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 vote down vote up
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 vote down vote up
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: FetchAddressWorker.java    From PhoneProfilesPlus with Apache License 2.0 4 votes vote down vote up
@NonNull
@Override
public Result doWork() {
    try {
        //PPApplication.logE("FetchAddressWorker.doWork", "xxx");

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

        Data outputData;

        // Get the input
        // Get the location passed to this service through an extra.
        double latitude = getInputData().getDouble(LocationGeofenceEditorActivity.LATITUDE_EXTRA, 0);
        double longitude = getInputData().getDouble(LocationGeofenceEditorActivity.LONGITUDE_EXTRA, 0);
        boolean updateName = getInputData().getBoolean(LocationGeofenceEditorActivity.UPDATE_NAME_EXTRA, false);

        Geocoder geocoder = new Geocoder(context, Locale.getDefault());

        List<Address> addresses = null;

        try {
            addresses = geocoder.getFromLocation(latitude, longitude,
                    // In this sample, get just a single address.
                    1);
        } catch (IOException ioException) {
            // Catch network or other I/O problems.
            //Log.e("FetchAddressWorker.doWork", "Service not available", ioException);
            //PPApplication.recordException(e);
        } catch (IllegalArgumentException illegalArgumentException) {
            // Catch invalid latitude or longitude values.
            /*Log.e("FetchAddressWorker.doWork", "Invalid location. " +
                    "Latitude = " + latitude +
                    ", Longitude = " +
                    longitude, illegalArgumentException);
            PPApplication.recordException(e);*/
        }

        // Handle case where no address was found.
        if (addresses == null || addresses.size() == 0) {
            //if (errorMessage.isEmpty()) {
            //Log.e("FetchAddressIntentService.onHandleIntent", "No address found");
            //}
            outputData = generateResult(LocationGeofenceEditorActivity.FAILURE_RESULT,
                    getApplicationContext().getString(R.string.event_preferences_location_no_address_found),
                    updateName);
        } else {
            Address address = addresses.get(0);
            ArrayList<String> addressFragments = new ArrayList<>();

            // Fetch the address lines using getAddressLine,
            // join them, and send them to the thread.
            for (int i = 0; i <= address.getMaxAddressLineIndex(); i++) {
                addressFragments.add(address.getAddressLine(i));
            }
            String lineSeparator = System.getProperty("line.separator");
            if (lineSeparator == null)
                lineSeparator = "\n";
            outputData = generateResult(LocationGeofenceEditorActivity.SUCCESS_RESULT,
                    TextUtils.join(lineSeparator, addressFragments),
                    updateName);
        }

        //if (outputData == null)
        //    return Result.success();
        //else
        // Return the output
        return Result.success(outputData);
    } catch (Exception e) {
        //Log.e("FetchAddressWorker.doWork", Log.getStackTraceString(e));
        PPApplication.recordException(e);
        return Result.failure();
    }
}
 
Example #23
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) {
                                }
                            }
                        }
                    }
                });
                */
            }
        }
    }
}
 
Example #24
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 #25
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 #26
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 #27
Source File: LocationUpdateWorker.java    From PixelWatchFace with GNU General Public License v3.0 4 votes vote down vote up
@NonNull
@Override
public ListenableFuture<Result> startWork() {
  String TAG = "location_update_worker";
  Log.d(TAG, "starting location work...");
  FusedLocationProviderClient fusedLocationClient = LocationServices
      .getFusedLocationProviderClient(getApplicationContext());

  return CallbackToFutureAdapter.getFuture(completer -> {
    if (ActivityCompat
        .checkSelfPermission(getApplicationContext(), permission.ACCESS_FINE_LOCATION)
        != PackageManager.PERMISSION_GRANTED
        && ActivityCompat
        .checkSelfPermission(getApplicationContext(), permission.ACCESS_COARSE_LOCATION)
        != PackageManager.PERMISSION_GRANTED) {
      completer.set(Result.failure());
    } else {
      fusedLocationClient.getLastLocation().addOnSuccessListener(location -> {
        if (location != null) {
          Log.d(TAG, "location: (" + location.getLatitude() + "," + location
              .getLongitude() + ")");
          //mCurrentWeather.setLocation(location);
          //Log.d(TAG, "gson-ized location: " + new Gson().toJson(location));
          Data output = new Data.Builder()
              .putDouble(KEY_LATITUDE, location.getLatitude())
              .putDouble(KEY_LONGITUDE, location.getLongitude())
              .putDouble(KEY_ALTITUDE, location.getAltitude())
              .putString(KEY_LOCATION_PROVIDER, location.getProvider())
              .build();

          completer.set(Result.success(output));
        } else {
          if (ActivityCompat.checkSelfPermission(getApplicationContext(),
              Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            completer.set(Result.failure());
          } else {
            // if no location, but permission exists, try again
            Log.d(TAG, "error retrieving location");
            completer.set(Result.retry());
          }
        }
      });
    }
    return completer;
  });
}
 
Example #28
Source File: LocalMutationSyncWorker.java    From ground-android with Apache License 2.0 4 votes vote down vote up
/** Returns a new work {@link Data} object containing the specified feature id. */
public static Data createInputData(String featureId) {
  return new Data.Builder().putString(FEATURE_ID_PARAM_KEY, featureId).build();
}
 
Example #29
Source File: PhotoSyncWorker.java    From ground-android with Apache License 2.0 4 votes vote down vote up
static Data createInputData(String sourceFilePath, String destinationPath) {
  return new Data.Builder()
      .putString(SOURCE_FILE_PATH_PARAM_KEY, sourceFilePath)
      .putString(DESTINATION_PATH_PARAM_KEY, destinationPath)
      .build();
}
 
Example #30
Source File: SyncMetadataWorker.java    From dhis2-android-capture-app with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private Data createOutputData(boolean state) {
    return new Data.Builder()
            .putBoolean("METADATA_STATE", state)
            .build();
}