Java Code Examples for androidx.work.WorkManager#enqueueUniqueWork()

The following examples show how to use androidx.work.WorkManager#enqueueUniqueWork() . 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 vote down vote up
private void markImportantNow(final Collection<String> threadIds) {
    requireDatabase().overwriteDao().insertMailboxOverwrites(
            MailboxOverwriteEntity.of(threadIds, Role.IMPORTANT, true)
    );
    deleteQueryItemOverwrite(threadIds, Role.IMPORTANT);
    final WorkManager workManager = WorkManager.getInstance(application);
    for(final String threadId : threadIds) {
        final OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(MarkImportantWorker.class)
                .setConstraints(CONNECTED_CONSTRAINT)
                .setInputData(MarkImportantWorker.data(requireAccount().id, threadId))
                .addTag(AbstractMuaWorker.TAG_EMAIL_MODIFICATION)
                .build();
        workManager.enqueueUniqueWork(
                MarkImportantWorker.uniqueName(threadId),
                ExistingWorkPolicy.REPLACE,
                workRequest
        );
    }
}
 
Example 2
Source File: LttrsRepository.java    From lttrs-android with Apache License 2.0 6 votes vote down vote up
private void markNotImportant(final Collection<String> threadIds, final IdentifiableMailboxWithRole mailbox) {
    Preconditions.checkArgument(mailbox.getRole() == Role.IMPORTANT);
    insertQueryItemOverwrite(threadIds, mailbox);
    requireDatabase().overwriteDao().insertMailboxOverwrites(
            MailboxOverwriteEntity.of(threadIds, Role.IMPORTANT, false)
    );
    final WorkManager workManager = WorkManager.getInstance(application);
    for(final String threadId : threadIds) {
        final OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(RemoveFromMailboxWorker.class)
                .setConstraints(CONNECTED_CONSTRAINT)
                .setInputData(RemoveFromMailboxWorker.data(requireAccount().id, threadId, mailbox))
                .addTag(AbstractMuaWorker.TAG_EMAIL_MODIFICATION)
                .setInitialDelay(INITIAL_DELAY_DURATION, INITIAL_DELAY_TIME_UNIT)
                .build();
        workManager.enqueueUniqueWork(
                MarkImportantWorker.uniqueName(threadId),
                ExistingWorkPolicy.REPLACE,
                workRequest
        );
    }
}
 
Example 3
Source File: AvoidRescheduleReceiverWorker.java    From PhoneProfilesPlus with Apache License 2.0 6 votes vote down vote up
static void enqueueWork() {
    PhoneProfilesService.cancelWork(PPApplication.AVOID_RESCHEDULE_RECEIVER_WORK_TAG);
    OneTimeWorkRequest avoidRescheduleReceiverWorker =
            new OneTimeWorkRequest.Builder(AvoidRescheduleReceiverWorker.class)
                    .addTag(PPApplication.AVOID_RESCHEDULE_RECEIVER_WORK_TAG)
                    .setInitialDelay(30 * 3, TimeUnit.DAYS)
                    .build();
    try {
        WorkManager workManager = PPApplication.getWorkManagerInstance();
        //PPApplication.logE("##### PPApplication.onCreate", "workManager="+workManager);
        if (workManager != null)
            workManager.enqueueUniqueWork(PPApplication.AVOID_RESCHEDULE_RECEIVER_WORK_TAG, ExistingWorkPolicy.KEEP, avoidRescheduleReceiverWorker);
    } catch (Exception e) {
        PPApplication.recordException(e);
    }
}
 
Example 4
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 5
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 6
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 7
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 8
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 9
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 10
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 11
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);
    */
}