Java Code Examples for android.app.AlarmManager#setAlarmClock()

The following examples show how to use android.app.AlarmManager#setAlarmClock() . 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: DataCollectionService.java    From NightWatch with GNU General Public License v3.0 8 votes vote down vote up
public void setAlarm() {
    long retry_in = (long) sleepTime();
    Log.d("DataCollectionService", "Next packet should be available in " + (retry_in / (60 * 1000)) + " minutes");
    Calendar calendar = Calendar.getInstance();
    AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
    long wakeTime = calendar.getTimeInMillis() + retry_in;
    Log.d(this.getClass().getName() , "ArmTimer waking at: "+ new Date(wakeTime) +" in " +  (wakeTime - calendar.getTimeInMillis())/60000d + " minutes");
    if (wakeIntent != null)
        alarm.cancel(wakeIntent);
    wakeIntent = PendingIntent.getService(this, 0, new Intent(this, this.getClass()), 0);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        alarm.setAlarmClock(new AlarmManager.AlarmClockInfo(wakeTime, wakeIntent), wakeIntent);
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        alarm.setExact(AlarmManager.RTC_WAKEUP, wakeTime, wakeIntent);
    } else {
        alarm.set(AlarmManager.RTC_WAKEUP, wakeTime, wakeIntent);
    }
}
 
Example 2
Source File: Publisher.java    From PresencePublisher with MIT License 7 votes vote down vote up
private void scheduleFor(long nextSchedule, boolean ignoreBattery) {
    AlarmManager alarmManager = (AlarmManager) applicationContext.getSystemService(Context.ALARM_SERVICE);
    if (alarmManager == null) {
        HyperLog.e(TAG, "Unable to get alarm manager, cannot schedule!");
        return;
    }
    alarmManager.cancel(scheduledIntent);
    HyperLog.i(TAG, "Next run at " + DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(new Date(nextSchedule)));
    sharedPreferences.edit().putLong(NEXT_SCHEDULE, nextSchedule).apply();
    NotificationManagerCompat.from(applicationContext)
            .notify(NOTIFICATION_ID, NotificationFactory.getNotification(applicationContext, lastSuccess, nextSchedule));
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ignoreBattery) {
            alarmManager.setAlarmClock(new AlarmManager.AlarmClockInfo(nextSchedule, scheduledIntent), scheduledIntent);
        } else {
            alarmManager.setAndAllowWhileIdle(RTC_WAKEUP, nextSchedule, scheduledIntent);
        }
    } else {
        alarmManager.set(RTC_WAKEUP, nextSchedule, scheduledIntent);
    }
}
 
Example 3
Source File: Notifications.java    From NightWatch with GNU General Public License v3.0 6 votes vote down vote up
private void ArmTimer(Context ctx) {
    Log.d(TAG, "ArmTimer called");
    ActiveBgAlert activeBgAlert = ActiveBgAlert.getOnly();
    if (activeBgAlert != null) {
        AlertType alert = AlertType.get_alert(activeBgAlert.alert_uuid);
        if (alert != null) {
            Calendar calendar = Calendar.getInstance();
            AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
            // sleep longer if the alert is snoozed.
            long wakeTime = activeBgAlert.next_alert_at;
            Log.d(TAG , "ArmTimer waking at: "+ new Date(wakeTime) +" in " +  (wakeTime - calendar.getTimeInMillis())/60000d + " minutes");
            if (wakeIntent != null)
                alarm.cancel(wakeIntent);
            wakeIntent = PendingIntent.getService(this, 0, new Intent(this, this.getClass()), 0);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                alarm.setAlarmClock(new AlarmManager.AlarmClockInfo(wakeTime, wakeIntent), wakeIntent);
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                alarm.setExact(AlarmManager.RTC_WAKEUP, wakeTime, wakeIntent);
            } else
                alarm.set(AlarmManager.RTC_WAKEUP, wakeTime, wakeIntent);
        }
    }
}
 
Example 4
Source File: EventPreferencesSMS.java    From PhoneProfilesPlus with Apache License 2.0 6 votes vote down vote up
@SuppressLint({"SimpleDateFormat", "NewApi"})
private void setAlarm(long alarmTime, Context context)
{
    if (!_permanentRun) {
        if (_startTime > 0) {
            /*if (PPApplication.logEnabled()) {
                SimpleDateFormat sdf = new SimpleDateFormat("EE d.MM.yyyy HH:mm:ss:S");
                String result = sdf.format(alarmTime);
                PPApplication.logE("EventPreferencesSMS.setAlarm", "endTime=" + result);
            }*/

            /*if (ApplicationPreferences.applicationUseAlarmClock(context)) {
                //Intent intent = new Intent(context, SMSEventEndBroadcastReceiver.class);
                Intent intent = new Intent();
                intent.setAction(PhoneProfilesService.ACTION_SMS_EVENT_END_BROADCAST_RECEIVER);
                //intent.setClass(context, SMSEventEndBroadcastReceiver.class);

                //intent.putExtra(PPApplication.EXTRA_EVENT_ID, _event._id);

                PendingIntent pendingIntent = PendingIntent.getBroadcast(context, (int) _event._id, intent, PendingIntent.FLAG_UPDATE_CURRENT);

                AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
                if (alarmManager != null) {
                    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 {
                Calendar now = Calendar.getInstance();
                long elapsedTime = (alarmTime + Event.EVENT_ALARM_TIME_OFFSET) - now.getTimeInMillis();

                if (PPApplication.logEnabled()) {
                    long allSeconds = elapsedTime / 1000;
                    long hours = allSeconds / 60 / 60;
                    long minutes = (allSeconds - (hours * 60 * 60)) / 60;
                    long seconds = allSeconds % 60;

                    PPApplication.logE("EventPreferencesSMS.setAlarm", "elapsedTime=" + hours + ":" + minutes + ":" + seconds);
                }

                Data workData = new Data.Builder()
                        .putString(PhoneProfilesService.EXTRA_ELAPSED_ALARMS_WORK, ElapsedAlarmsWorker.ELAPSED_ALARMS_SMS_EVENT_END_SENSOR)
                        .build();

                OneTimeWorkRequest worker =
                        new OneTimeWorkRequest.Builder(ElapsedAlarmsWorker.class)
                                .addTag("elapsedAlarmsSMSSensorWork_"+(int)_event._id)
                                .setInputData(workData)
                                .setInitialDelay(elapsedTime, TimeUnit.MILLISECONDS)
                                .build();
                try {
                    WorkManager workManager = WorkManager.getInstance(context);
                    PPApplication.logE("[HANDLER] EventPreferencesSMS.setAlarm", "enqueueUniqueWork - elapsedTime="+elapsedTime);
                    //workManager.enqueueUniqueWork("elapsedAlarmsSMSSensorWork_"+(int)_event._id, ExistingWorkPolicy.KEEP, worker);
                    workManager.enqueue(worker);
                } catch (Exception ignored) {}
            }*/

            //Intent intent = new Intent(context, SMSEventEndBroadcastReceiver.class);
            Intent intent = new Intent();
            intent.setAction(PhoneProfilesService.ACTION_SMS_EVENT_END_BROADCAST_RECEIVER);
            //intent.setClass(context, SMSEventEndBroadcastReceiver.class);

            //intent.putExtra(PPApplication.EXTRA_EVENT_ID, _event._id);

            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, (int) _event._id, intent, PendingIntent.FLAG_UPDATE_CURRENT);

            AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            if (alarmManager != null) {
                if (ApplicationPreferences.applicationUseAlarmClock) {
                    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 {
                    //if (android.os.Build.VERSION.SDK_INT >= 23)
                        alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, alarmTime + Event.EVENT_ALARM_TIME_OFFSET, pendingIntent);
                    //else //if (android.os.Build.VERSION.SDK_INT >= 19)
                    //    alarmManager.setExact(AlarmManager.RTC_WAKEUP, alarmTime + Event.EVENT_ALARM_TIME_OFFSET, pendingIntent);
                    //else
                    //    alarmManager.set(AlarmManager.RTC_WAKEUP, alarmTime + Event.EVENT_ALARM_TIME_OFFSET, pendingIntent);
                }
            }
        }
    }
}
 
Example 5
Source File: JoH.java    From xDrip with GNU General Public License v3.0 6 votes vote down vote up
public static long wakeUpIntent(Context context, long delayMs, PendingIntent pendingIntent) {
    final long wakeTime = JoH.tsl() + delayMs;
    if (pendingIntent != null) {
        Log.d(TAG, "Scheduling wakeup intent: " + dateTimeText(wakeTime));
        final AlarmManager alarm = (AlarmManager) context.getSystemService(ALARM_SERVICE);
        try {
            alarm.cancel(pendingIntent);
        } catch (Exception e) {
            Log.e(TAG, "Exception cancelling alarm in wakeUpIntent: " + e);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (buggy_samsung) {
                alarm.setAlarmClock(new AlarmManager.AlarmClockInfo(wakeTime, null), pendingIntent);
            } else {
                alarm.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, wakeTime, pendingIntent);
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            alarm.setExact(AlarmManager.RTC_WAKEUP, wakeTime, pendingIntent);
        } else
            alarm.set(AlarmManager.RTC_WAKEUP, wakeTime, pendingIntent);
    } else {
        Log.e(TAG, "wakeUpIntent - pending intent was null!");
    }
    return wakeTime;
}
 
Example 6
Source File: Notifications.java    From NightWatch with GNU General Public License v3.0 6 votes vote down vote up
private void ArmTimer(Context ctx) {
    Log.d(TAG, "ArmTimer called");
    ActiveBgAlert activeBgAlert = ActiveBgAlert.getOnly();
    if (activeBgAlert != null) {
        AlertType alert = AlertType.get_alert(activeBgAlert.alert_uuid);
        if (alert != null) {
            Calendar calendar = Calendar.getInstance();
            AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
            // sleep longer if the alert is snoozed.
            long wakeTime = activeBgAlert.next_alert_at;
            Log.d(TAG , "ArmTimer waking at: "+ new Date(wakeTime) +" in " +  (wakeTime - calendar.getTimeInMillis())/60000d + " minutes");
            if (wakeIntent != null)
                alarm.cancel(wakeIntent);
            wakeIntent = PendingIntent.getService(this, 0, new Intent(this, this.getClass()), 0);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                alarm.setAlarmClock(new AlarmManager.AlarmClockInfo(wakeTime, wakeIntent), wakeIntent);
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                alarm.setExact(AlarmManager.RTC_WAKEUP, wakeTime, wakeIntent);
            } else
                alarm.set(AlarmManager.RTC_WAKEUP, wakeTime, wakeIntent);
        }
    }
}
 
Example 7
Source File: JoH.java    From xDrip-plus with GNU General Public License v3.0 6 votes vote down vote up
public static long wakeUpIntent(Context context, long delayMs, PendingIntent pendingIntent) {
    final long wakeTime = JoH.tsl() + delayMs;
    if (pendingIntent != null) {
        Log.d(TAG, "Scheduling wakeup intent: " + dateTimeText(wakeTime));
        final AlarmManager alarm = (AlarmManager) context.getSystemService(ALARM_SERVICE);
        try {
            alarm.cancel(pendingIntent);
        } catch (Exception e) {
            Log.e(TAG, "Exception cancelling alarm in wakeUpIntent: " + e);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (buggy_samsung) {
                alarm.setAlarmClock(new AlarmManager.AlarmClockInfo(wakeTime, null), pendingIntent);
            } else {
                alarm.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, wakeTime, pendingIntent);
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            alarm.setExact(AlarmManager.RTC_WAKEUP, wakeTime, pendingIntent);
        } else
            alarm.set(AlarmManager.RTC_WAKEUP, wakeTime, pendingIntent);
    } else {
        Log.e(TAG, "wakeUpIntent - pending intent was null!");
    }
    return wakeTime;
}
 
Example 8
Source File: AlarmScheduler.java    From BaldPhone with Apache License 2.0 5 votes vote down vote up
public static void scheduleAlarm(@NonNull Alarm alarm, @NonNull Context context) throws IllegalArgumentException {
    synchronized (LOCK) {
        S.logImportant("Scheduling an alarm!");
        final AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        final long nextTimeAlarmWillWorkInMs = nextTimeAlarmWillWorkInMs(alarm);
        alarmManager.setAlarmClock(
                new AlarmManager.AlarmClockInfo(
                        nextTimeAlarmWillWorkInMs,
                        PendingIntent.getActivity(context, 0, new Intent(context, AlarmsActivity.class), 0)
                ),
                getIntent(context, alarm.getKey())
        );
    }
}
 
Example 9
Source File: AlarmNotifications.java    From SuntimesWidget with GNU General Public License v3.0 5 votes vote down vote up
protected static void addAlarmTimeout(Context context, @NonNull AlarmManager alarmManager, String action, Uri data, long timeoutAt, int type)
{
    Log.d(TAG, "addAlarmTimeout: " + action + ": " + data + " (wakeup:" + type + ")");
    if (action.equals(ACTION_SHOW))
    {
        if (Build.VERSION.SDK_INT >= 21)
        {
            PendingIntent showAlarmIntent = PendingIntent.getActivity(context, 0, getAlarmListIntent(context, ContentUris.parseId(data)), 0);
            AlarmManager.AlarmClockInfo alarmInfo = new AlarmManager.AlarmClockInfo(timeoutAt, showAlarmIntent);
            alarmManager.setAlarmClock(alarmInfo, getPendingIntent(context, action, data));

        } else if (Build.VERSION.SDK_INT >= 19) {
            alarmManager.setExact(type, timeoutAt, getPendingIntent(context, action, data));

        } else alarmManager.set(type, timeoutAt, getPendingIntent(context, action, data));

    } else {
        // ACTION_SCHEDULE, ACTION_SILENCE, ACTION_SNOOZE, ACTION_TIMEOUT
        if (Build.VERSION.SDK_INT >= 23) {
            alarmManager.setExactAndAllowWhileIdle(type, timeoutAt, getPendingIntent(context, action, data));

        } else if (Build.VERSION.SDK_INT >= 19) {
            alarmManager.setExact(type, timeoutAt, getPendingIntent(context, action, data));

        } else alarmManager.set(type, timeoutAt, getPendingIntent(context, action, data));
    }
}
 
Example 10
Source File: Notifications.java    From xDrip-Experimental with GNU General Public License v3.0 5 votes vote down vote up
private void ArmTimer(Context ctx, boolean unclearAlert) {
    Calendar calendar = Calendar.getInstance();
    final long now = calendar.getTimeInMillis();
    Log.d("Notifications", "ArmTimer called");

    long wakeTime = calcuatleArmTime(ctx, now, unclearAlert);

    
    if(wakeTime < now || wakeTime == Long.MAX_VALUE) {
      Log.e("Notifications" , "ArmTimer recieved a negative time, will fire in 6 minutes");
      wakeTime = now + 6 * 60000;
    }
    
    AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);

    
    Log.d("Notifications" , "ArmTimer waking at: "+ new Date(wakeTime ) +" in " +
        (wakeTime - now) /60000d + " minutes");
    if (wakeIntent != null)
        alarm.cancel(wakeIntent);
    wakeIntent = PendingIntent.getService(this, 0, new Intent(this, this.getClass()), 0);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        alarm.setAlarmClock(new AlarmManager.AlarmClockInfo(wakeTime, wakeIntent), wakeIntent);
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        alarm.setExact(AlarmManager.RTC_WAKEUP, wakeTime, wakeIntent);
    } else {
        alarm.set(AlarmManager.RTC_WAKEUP, wakeTime, wakeIntent);
    }
}
 
Example 11
Source File: MyActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 5 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.M)
private void listing11_32_to_34() {
  // Listing 11-32: Creating an alarm that triggers at the top of the hour
  // Get a reference to the Alarm Manager
  AlarmManager alarmManager =
    (AlarmManager) getSystemService(Context.ALARM_SERVICE);

  // Find the trigger time
  Calendar calendar = Calendar.getInstance();
  calendar.set(Calendar.MINUTE, 0);
  calendar.set(Calendar.SECOND, 0);
  calendar.set(Calendar.MILLISECOND, 0);
  calendar.add(Calendar.HOUR, 1);
  long time = calendar.getTimeInMillis();

  // Create a Pending Intent that will broadcast and action
  String ALARM_ACTION = "ALARM_ACTION";
  Intent intentToFire = new Intent(ALARM_ACTION);
  PendingIntent alarmIntent = PendingIntent.getBroadcast(this, 0,
    intentToFire, 0);

  // Set the alarm
  alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, time, alarmIntent);

  // LISTING 11-33: Canceling an Alarm
  alarmManager.cancel(alarmIntent);

  // Listing 11-34: Setting an Alarm Clock
  // Create a Pending Intent that can be used to show or edit the alarm clock
  // when the alarm clock icon is touched
  Intent alarmClockDetails = new Intent(this, AlarmClockActivity.class);

  PendingIntent showIntent = PendingIntent.getActivity(this, 0,
    alarmClockDetails, 0);

  // Set the alarm clock, which will fire the alarmIntent at the set time
  alarmManager.setAlarmClock(
    new AlarmManager.AlarmClockInfo(time, showIntent),
    alarmIntent);
}
 
Example 12
Source File: ReminderScheduler.java    From BaldPhone with Apache License 2.0 5 votes vote down vote up
public static void scheduleSnooze(@NonNull Reminder alarm, Context context) throws IllegalArgumentException {
    synchronized (LOCK) {
        final AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.setAlarmClock(
                new AlarmManager.AlarmClockInfo(
                        DateTime.now().getMillis() + SNOOZE_MILLIS,
                        PendingIntent.getActivity(context, alarm.getId(), new Intent(context, HomeScreenActivity.class), 0)//TODO??
                ),
                getIntent(context, alarm.getId())
        );
    }
}
 
Example 13
Source File: ReminderScheduler.java    From BaldPhone with Apache License 2.0 5 votes vote down vote up
public static void scheduleReminder(@NonNull Reminder reminder, @NonNull Context context) throws IllegalArgumentException {
    synchronized (LOCK) {
        final AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        final long nextTimeReminderWillWorkInMs = nextTimeReminderWillWorkInMs(reminder, context);
        alarmManager.setAlarmClock(
                new AlarmManager.AlarmClockInfo(
                        nextTimeReminderWillWorkInMs,
                        PendingIntent.getActivity(context, 0, new Intent(context, PillsActivity.class), 0)
                ),
                getIntent(context, reminder.getId())
        );
    }
}
 
Example 14
Source File: EventPreferencesAlarmClock.java    From PhoneProfilesPlus with Apache License 2.0 4 votes vote down vote up
@SuppressLint({"SimpleDateFormat", "NewApi"})
private void setAlarm(long alarmTime, Context context)
{
    if (!_permanentRun) {
        if (_startTime > 0) {
            /*if (PPApplication.logEnabled()) {
                SimpleDateFormat sdf = new SimpleDateFormat("EE d.MM.yyyy HH:mm:ss:S");
                String result = sdf.format(alarmTime);
                PPApplication.logE("EventPreferencesAlarmClock.setAlarm", "endTime=" + result);
            }*/

            /*if (ApplicationPreferences.applicationUseAlarmClock(context)) {
                Intent intent = new Intent();
                intent.setAction(PhoneProfilesService.ACTION_ALARM_CLOCK_EVENT_END_BROADCAST_RECEIVER);

                //intent.putExtra(PPApplication.EXTRA_EVENT_ID, _event._id);

                PendingIntent pendingIntent = PendingIntent.getBroadcast(context, (int) _event._id, intent, PendingIntent.FLAG_UPDATE_CURRENT);

                AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
                if (alarmManager != null) {
                    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 {
                Calendar now = Calendar.getInstance();
                long elapsedTime = (alarmTime + Event.EVENT_ALARM_TIME_OFFSET) - now.getTimeInMillis();

                if (PPApplication.logEnabled()) {
                    long allSeconds = elapsedTime / 1000;
                    long hours = allSeconds / 60 / 60;
                    long minutes = (allSeconds - (hours * 60 * 60)) / 60;
                    long seconds = allSeconds % 60;

                    PPApplication.logE("EventPreferencesAlarmClock.setAlarm", "elapsedTime=" + hours + ":" + minutes + ":" + seconds);
                }

                Data workData = new Data.Builder()
                        .putString(PhoneProfilesService.EXTRA_ELAPSED_ALARMS_WORK, ElapsedAlarmsWorker.ELAPSED_ALARMS_ALARM_CLOCK_EVENT_END_SENSOR)
                        .build();

                OneTimeWorkRequest worker =
                        new OneTimeWorkRequest.Builder(ElapsedAlarmsWorker.class)
                                .addTag("elapsedAlarmsAlarmClockSensorWork_"+(int)_event._id)
                                .setInputData(workData)
                                .setInitialDelay(elapsedTime, TimeUnit.MILLISECONDS)
                                .build();
                try {
                    WorkManager workManager = WorkManager.getInstance(context);
                    PPApplication.logE("[HANDLER] EventPreferencesAlarmClock.setAlarm", "enqueueUniqueWork - elapsedTime="+elapsedTime);
                    //workManager.enqueueUniqueWork("elapsedAlarmsAlarmClockSensorWork_"+(int)_event._id, ExistingWorkPolicy.KEEP, worker);
                    workManager.enqueue(worker);
                } catch (Exception ignored) {}
            }*/

            Intent intent = new Intent();
            intent.setAction(PhoneProfilesService.ACTION_ALARM_CLOCK_EVENT_END_BROADCAST_RECEIVER);

            //intent.putExtra(PPApplication.EXTRA_EVENT_ID, _event._id);

            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, (int) _event._id, intent, PendingIntent.FLAG_UPDATE_CURRENT);

            AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            if (alarmManager != null) {
                if (ApplicationPreferences.applicationUseAlarmClock) {
                    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 {
                    //if (android.os.Build.VERSION.SDK_INT >= 23)
                        alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, alarmTime + Event.EVENT_ALARM_TIME_OFFSET, pendingIntent);
                    //else //if (android.os.Build.VERSION.SDK_INT >= 19)
                    //    alarmManager.setExact(AlarmManager.RTC_WAKEUP, alarmTime + Event.EVENT_ALARM_TIME_OFFSET, pendingIntent);
                    //else
                    //    alarmManager.set(AlarmManager.RTC_WAKEUP, alarmTime + Event.EVENT_ALARM_TIME_OFFSET, pendingIntent);
                }
            }
        }
    }
}
 
Example 15
Source File: AlarmController.java    From ClockPlus with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Schedules the alarm with the {@link AlarmManager}.
 * If {@code alarm.}{@link Alarm#isEnabled() isEnabled()}
 * returns false, this does nothing and returns immediately.
 * 
 * If there is already an alarm for this Intent scheduled (with the equality of two
 * intents being defined by filterEquals(Intent)), then it will be removed and replaced
 * by this one. For most of our uses, the relevant criteria for equality will be the
 * action, the data, and the class (component). Although not documented, the request code
 * of a PendingIntent is also considered to determine equality of two intents.
 */
public void scheduleAlarm(Alarm alarm, boolean showSnackbar) {
    if (!alarm.isEnabled()) {
        return;
    }
    // Does nothing if it's not posted. This is primarily here for when alarms
    // are updated, instead of newly created, so that we don't leave behind
    // stray upcoming alarm notifications. This occurs e.g. when a single-use
    // alarm is updated to recur on a weekday later than the current day.
    removeUpcomingAlarmNotification(alarm);

    AlarmManager am = (AlarmManager) mAppContext.getSystemService(Context.ALARM_SERVICE);

    final long ringAt = alarm.isSnoozed() ? alarm.snoozingUntil() : alarm.ringsAt();
    final PendingIntent alarmIntent = alarmIntent(alarm, false);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        PendingIntent showIntent = ContentIntentUtils.create(mAppContext, MainActivity.PAGE_ALARMS, alarm.getId());
        AlarmManager.AlarmClockInfo info = new AlarmManager.AlarmClockInfo(ringAt, showIntent);
        am.setAlarmClock(info, alarmIntent);
    } else {
        // WAKEUP alarm types wake the CPU up, but NOT the screen;
        // you would handle that yourself by using a wakelock, etc..
        am.setExact(AlarmManager.RTC_WAKEUP, ringAt, alarmIntent);
        // Show alarm in the status bar
        Intent alarmChanged = new Intent("android.intent.action.ALARM_CHANGED");
        alarmChanged.putExtra("alarmSet", true/*enabled*/);
        mAppContext.sendBroadcast(alarmChanged);
    }

    final int hoursToNotifyInAdvance = AlarmPreferences.hoursBeforeUpcoming(mAppContext);
    if (hoursToNotifyInAdvance > 0 || alarm.isSnoozed()) {
        // If snoozed, upcoming note posted immediately.
        long upcomingAt = ringAt - HOURS.toMillis(hoursToNotifyInAdvance);
        // We use a WAKEUP alarm to send the upcoming alarm notification so it goes off even if the
        // device is asleep. Otherwise, it will not go off until the device is turned back on.
        am.set(AlarmManager.RTC_WAKEUP, upcomingAt, notifyUpcomingAlarmIntent(alarm, false));
    }

    if (showSnackbar) {
        String message = mAppContext.getString(R.string.alarm_set_for,
                DurationUtils.toString(mAppContext, alarm.ringsIn(), false/*abbreviate*/));
        showSnackbar(message);
    }
}
 
Example 16
Source File: EventPreferencesCall.java    From PhoneProfilesPlus with Apache License 2.0 4 votes vote down vote up
@SuppressLint("NewApi")
private void setAlarm(long alarmTime, Context context) {
    if (!_permanentRun) {
        if (_startTime > 0) {
            /*if (PPApplication.logEnabled()) {
                @SuppressLint("SimpleDateFormat")
                SimpleDateFormat sdf = new SimpleDateFormat("EE d.MM.yyyy HH:mm:ss:S");
                String result = sdf.format(alarmTime);
                PPApplication.logE("EventPreferencesCall.setAlarm", "endTime=" + result);
            }*/

            /*if (ApplicationPreferences.applicationUseAlarmClock(context)) {
                //Intent intent = new Intent(context, MissedCallEventEndBroadcastReceiver.class);
                Intent intent = new Intent();
                intent.setAction(PhoneProfilesService.ACTION_MISSED_CALL_EVENT_END_BROADCAST_RECEIVER);
                //intent.setClass(context, MissedCallEventEndBroadcastReceiver.class);

                //intent.putExtra(PPApplication.EXTRA_EVENT_ID, _event._id);

                PendingIntent pendingIntent = PendingIntent.getBroadcast(context, (int) _event._id, intent, PendingIntent.FLAG_UPDATE_CURRENT);

                AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
                if (alarmManager != null) {
                    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 {
                Calendar now = Calendar.getInstance();
                long elapsedTime = (alarmTime + Event.EVENT_ALARM_TIME_OFFSET) - now.getTimeInMillis();

                if (PPApplication.logEnabled()) {
                    long allSeconds = elapsedTime / 1000;
                    long hours = allSeconds / 60 / 60;
                    long minutes = (allSeconds - (hours * 60 * 60)) / 60;
                    long seconds = allSeconds % 60;

                    PPApplication.logE("EventPreferencesCall.setAlarm", "elapsedTime=" + hours + ":" + minutes + ":" + seconds);
                }

                Data workData = new Data.Builder()
                        .putString(PhoneProfilesService.EXTRA_ELAPSED_ALARMS_WORK, ElapsedAlarmsWorker.ELAPSED_ALARMS_CALL_SENSOR)
                        .build();

                OneTimeWorkRequest worker =
                        new OneTimeWorkRequest.Builder(ElapsedAlarmsWorker.class)
                                .addTag("elapsedAlarmsCallSensorWork_"+(int)_event._id)
                                .setInputData(workData)
                                .setInitialDelay(elapsedTime, TimeUnit.MILLISECONDS)
                                .build();
                try {
                    WorkManager workManager = WorkManager.getInstance(context);
                    PPApplication.logE("[HANDLER] EventPreferencesCall.setAlarm", "enqueueUniqueWork - elapsedTime="+elapsedTime);
                    //workManager.enqueueUniqueWork("elapsedAlarmsCallSensorWork_"+(int)_event._id, ExistingWorkPolicy.KEEP, worker);
                    workManager.enqueue(worker);
                } catch (Exception ignored) {}
            }*/

            //Intent intent = new Intent(context, MissedCallEventEndBroadcastReceiver.class);
            Intent intent = new Intent();
            intent.setAction(PhoneProfilesService.ACTION_MISSED_CALL_EVENT_END_BROADCAST_RECEIVER);
            //intent.setClass(context, MissedCallEventEndBroadcastReceiver.class);

            //intent.putExtra(PPApplication.EXTRA_EVENT_ID, _event._id);

            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, (int) _event._id, intent, PendingIntent.FLAG_UPDATE_CURRENT);

            AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            if (alarmManager != null) {
                if (ApplicationPreferences.applicationUseAlarmClock) {
                    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 {
                    //if (android.os.Build.VERSION.SDK_INT >= 23)
                        alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, alarmTime + Event.EVENT_ALARM_TIME_OFFSET, pendingIntent);
                    //else //if (android.os.Build.VERSION.SDK_INT >= 19)
                    //    alarmManager.setExact(AlarmManager.RTC_WAKEUP, alarmTime + Event.EVENT_ALARM_TIME_OFFSET, pendingIntent);
                    //else
                    //    alarmManager.set(AlarmManager.RTC_WAKEUP, alarmTime + Event.EVENT_ALARM_TIME_OFFSET, pendingIntent);
                }
            }
        }
    }
}
 
Example 17
Source File: DonationBroadcastReceiver.java    From PhoneProfilesPlus with Apache License 2.0 4 votes vote down vote up
static public void setAlarm(Context context)
{
    removeAlarm(context);

    Calendar now = Calendar.getInstance();
    //if (DebugVersion.enabled) {
    //    now.add(Calendar.MINUTE, 1);
    //} else {
        // each day at 13:30
        now.set(Calendar.HOUR_OF_DAY, 13);
        now.set(Calendar.MINUTE, 30);
        now.add(Calendar.DAY_OF_MONTH, 1);
        now.set(Calendar.SECOND, 0);
        now.set(Calendar.MILLISECOND, 0);
    //}

    long alarmTime = now.getTimeInMillis();

    /*if (ApplicationPreferences.applicationUseAlarmClock(context)) {
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        if (alarmManager != null) {
            //Intent intent = new Intent(_context, DonationBroadcastReceiver.class);
            Intent intent = new Intent();
            intent.setAction(PPApplication.ACTION_DONATION);
            //intent.setClass(context, DonationBroadcastReceiver.class);

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

            PPApplication.logE("DonationBroadcastReceiver.setAlarm",
                    "alarmTime=" + DateFormat.getDateFormat(context).format(alarmTime) +
                            " " + DateFormat.getTimeFormat(context).format(alarmTime));

            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 {
        now = Calendar.getInstance();
        long elapsedTime = alarmTime - now.getTimeInMillis();

        if (PPApplication.logEnabled()) {
            long allSeconds = elapsedTime / 1000;
            long hours = allSeconds / 60 / 60;
            long minutes = (allSeconds - (hours * 60 * 60)) / 60;
            long seconds = allSeconds % 60;

            PPApplication.logE("DonationBroadcastReceiver.setAlarm", "elapsedTime=" + hours + ":" + minutes + ":" + seconds);
        }

        Data workData = new Data.Builder()
                .putString(PhoneProfilesService.EXTRA_ELAPSED_ALARMS_WORK, ElapsedAlarmsWorker.ELAPSED_ALARMS_DONATION)
                .build();

        OneTimeWorkRequest worker =
                new OneTimeWorkRequest.Builder(ElapsedAlarmsWorker.class)
                        .addTag("elapsedAlarmsDonationWork")
                        .setInputData(workData)
                        .setInitialDelay(elapsedTime, TimeUnit.MILLISECONDS)
                        .build();
        try {
            WorkManager workManager = WorkManager.getInstance(context);
            PPApplication.logE("[HANDLER] DonationBroadcastReceiver.setAlarm", "enqueueUniqueWork - elapsedTime="+elapsedTime);
            workManager.enqueueUniqueWork("elapsedAlarmsDonationWork", ExistingWorkPolicy.KEEP, worker);
        } catch (Exception ignored) {}
    }*/

    //Intent intent = new Intent(_context, DonationBroadcastReceiver.class);
    Intent intent = new Intent();
    intent.setAction(PPApplication.ACTION_DONATION);
    //intent.setClass(context, DonationBroadcastReceiver.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) {
            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 {
            //if (android.os.Build.VERSION.SDK_INT >= 23)
                alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent);
            //else //if (android.os.Build.VERSION.SDK_INT >= 19)
            //    alarmManager.setExact(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent);
            //else
            //    alarmManager.set(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent);
        }
    }
}
 
Example 18
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 19
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 20
Source File: EventPreferencesDeviceBoot.java    From PhoneProfilesPlus with Apache License 2.0 4 votes vote down vote up
@SuppressLint({"SimpleDateFormat", "NewApi"})
private void setAlarm(long alarmTime, Context context)
{
    //PPApplication.logE("[BOOT] EventPreferencesDeviceBoot.setAlarm","_permanentRun="+_permanentRun);
    //PPApplication.logE("[BOOT] EventPreferencesDeviceBoot.setAlarm","_startTime="+_startTime);

    if (!_permanentRun) {
        if (_startTime > 0) {
            /*if (PPApplication.logEnabled()) {
                SimpleDateFormat sdf = new SimpleDateFormat("EE d.MM.yyyy HH:mm:ss:S");
                String result = sdf.format(alarmTime);
                PPApplication.logE("[BOOT] EventPreferencesDeviceBoot.setAlarm", "endTime=" + result);
            }*/

            /*if (ApplicationPreferences.applicationUseAlarmClock(context)) {
                Intent intent = new Intent();
                intent.setAction(PhoneProfilesService.ACTION_DEVICE_BOOT_EVENT_END_BROADCAST_RECEIVER);

                //intent.putExtra(PPApplication.EXTRA_EVENT_ID, _event._id);

                PendingIntent pendingIntent = PendingIntent.getBroadcast(context, (int) _event._id, intent, PendingIntent.FLAG_UPDATE_CURRENT);

                AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
                if (alarmManager != null) {
                    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 {
                Calendar now = Calendar.getInstance();
                long elapsedTime = (alarmTime + Event.EVENT_ALARM_TIME_OFFSET) - now.getTimeInMillis();

                if (PPApplication.logEnabled()) {
                    long allSeconds = elapsedTime / 1000;
                    long hours = allSeconds / 60 / 60;
                    long minutes = (allSeconds - (hours * 60 * 60)) / 60;
                    long seconds = allSeconds % 60;

                    PPApplication.logE("EventPreferencesDeviceBoot.setAlarm", "elapsedTime=" + hours + ":" + minutes + ":" + seconds);
                }

                Data workData = new Data.Builder()
                        .putString(PhoneProfilesService.EXTRA_ELAPSED_ALARMS_WORK, ElapsedAlarmsWorker.ELAPSED_ALARMS_DEVICE_BOOT_EVENT_END_SENSOR)
                        .build();

                OneTimeWorkRequest worker =
                        new OneTimeWorkRequest.Builder(ElapsedAlarmsWorker.class)
                                .addTag("elapsedAlarmsDeviceBootSensorWork_"+(int)_event._id)
                                .setInputData(workData)
                                .setInitialDelay(elapsedTime, TimeUnit.MILLISECONDS)
                                .build();
                try {
                    WorkManager workManager = WorkManager.getInstance(context);
                    PPApplication.logE("[HANDLER] EventPreferencesDeviceBoot.setAlarm", "enqueueUniqueWork - elapsedTime="+elapsedTime);
                    //workManager.enqueueUniqueWork("elapsedAlarmsDeviceBootSensorWork_"+(int)_event._id, ExistingWorkPolicy.KEEP, worker);
                    workManager.enqueue(worker);
                } catch (Exception ignored) {}
            }*/

            Intent intent = new Intent();
            intent.setAction(PhoneProfilesService.ACTION_DEVICE_BOOT_EVENT_END_BROADCAST_RECEIVER);

            //intent.putExtra(PPApplication.EXTRA_EVENT_ID, _event._id);

            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, (int) _event._id, intent, PendingIntent.FLAG_UPDATE_CURRENT);

            AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            if (alarmManager != null) {
                if (ApplicationPreferences.applicationUseAlarmClock) {
                    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 {
                    //if (android.os.Build.VERSION.SDK_INT >= 23)
                        alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, alarmTime + Event.EVENT_ALARM_TIME_OFFSET, pendingIntent);
                    //else //if (android.os.Build.VERSION.SDK_INT >= 19)
                    //    alarmManager.setExact(AlarmManager.RTC_WAKEUP, alarmTime + Event.EVENT_ALARM_TIME_OFFSET, pendingIntent);
                    //else
                    //    alarmManager.set(AlarmManager.RTC_WAKEUP, alarmTime + Event.EVENT_ALARM_TIME_OFFSET, pendingIntent);
                }
            }
        }
    }
}