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

The following examples show how to use android.app.AlarmManager#setExactAndAllowWhileIdle() . 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: DexShareCollectionService.java    From xDrip with GNU General Public License v3.0 6 votes vote down vote up
public void setRetryTimer() {
    if (CollectionServiceStarter.isBTShare(getApplicationContext())) {
        BgReading bgReading = BgReading.last();
        long retry_in;
        if (bgReading != null) {
            retry_in = Math.min(Math.max((1000 * 30), (1000 * 60 * 5) - (new Date().getTime() - bgReading.timestamp) + (1000 * 5)), (1000 * 60 * 5));
        } else {
            retry_in = (1000 * 20);
        }
        Log.d(TAG, "Restarting in: " + (retry_in / (60 * 1000)) + " minutes");
        Calendar calendar = Calendar.getInstance();
        AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
        if (pendingIntent != null)
            alarm.cancel(pendingIntent);
        long wakeTime = calendar.getTimeInMillis() + retry_in;
        pendingIntent = PendingIntent.getService(this, 0, new Intent(this, this.getClass()),  PendingIntent.FLAG_UPDATE_CURRENT);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            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);
    }
}
 
Example 2
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 3
Source File: KeyCachingService.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
private void scheduleTimeout(long timeoutSeconds) {
  if (pendingAlarm) return;

  Log.i(TAG, "Starting timeout: " + timeoutSeconds + " s.");

  long at = SystemClock.elapsedRealtime() + TimeUnit.SECONDS.toMillis(timeoutSeconds);

  AlarmManager alarmManager = ServiceUtil.getAlarmManager(this);
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    alarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, at, buildExpirationIntent());
  } else {
    alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, at, buildExpirationIntent());
  }

  pendingAlarm = true;
}
 
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: AppAlarmService.java    From your-local-weather with GNU General Public License v3.0 6 votes vote down vote up
private static void scheduleNextRegularAlarm(Context context, boolean autoLocation, long updatePeriodMilis) {
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    appendLog(context, TAG, "Build.VERSION.SDK_INT:", Build.VERSION.SDK_INT);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        alarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                SystemClock.elapsedRealtime() + updatePeriodMilis,
                getPendingIntent(context, autoLocation));
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                SystemClock.elapsedRealtime() + updatePeriodMilis,
                getPendingIntent(context, autoLocation));
    } else {
        alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                SystemClock.elapsedRealtime() + updatePeriodMilis,
                getPendingIntent(context, autoLocation));
    }
}
 
Example 6
Source File: WidgetUpdateService.java    From NightWatch with GNU General Public License v3.0 6 votes vote down vote up
public void setFailoverTimer() { //Keep it alive!
    if(AppWidgetManager.getInstance(getApplication()).getAppWidgetIds(new ComponentName(getApplication(), NightWatchWidget.class)).length > 0
            || AppWidgetManager.getInstance(getApplication()).getAppWidgetIds(new ComponentName(getApplication(), NightWatchWidgetWide.class)).length > 0) {
        long retry_in = (1000 * 60 * 5);
        Log.d(TAG, "Fallover Restarting in: " + (retry_in / (60 * 1000)) + " minutes");
        Calendar calendar = Calendar.getInstance();
        AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // Adrian: do we even need to handle non-awake systems? Updating views on non-awake systems seems pointless.
            alarm.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis() + retry_in, PendingIntent.getService(this, 0, new Intent(this, WidgetUpdateService.class), 0));
        } else if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            alarm.setExact(alarm.RTC_WAKEUP, calendar.getTimeInMillis() + retry_in, PendingIntent.getService(this, 0, new Intent(this, WidgetUpdateService.class), 0));
        } else {
            alarm.set(alarm.RTC_WAKEUP, calendar.getTimeInMillis() + retry_in, PendingIntent.getService(this, 0, new Intent(this, WidgetUpdateService.class), 0));

        }
    } else {
        stopSelf();
    }
}
 
Example 7
Source File: RealtimeSleepTimer.java    From libsignal-service-java with GNU General Public License v3.0 6 votes vote down vote up
private void setAlarm(long millis) {
  final Intent        intent        = new Intent(WAKE_UP_THREAD_ACTION);
  final PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
  final AlarmManager  alarmManager  = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);

  Log.w(TAG, "Setting alarm to wake up in " + millis + "ms.");

  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    alarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                                           SystemClock.elapsedRealtime() + millis,
                                           pendingIntent);
  } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                          SystemClock.elapsedRealtime() + millis,
                          pendingIntent);
  } else {
    alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                     SystemClock.elapsedRealtime() + millis,
                     pendingIntent);
  }
}
 
Example 8
Source File: BackgroundService.java    From BackPackTrackII with GNU General Public License v3.0 6 votes vote down vote up
public static void startDaily(Context context) {
    Intent alarmIntent = new Intent(context, BackgroundService.class);
    alarmIntent.setAction(BackgroundService.ACTION_DAILY);
    PendingIntent pi = PendingIntent.getService(context, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    long trigger = calendar.getTimeInMillis() + 24 * 3600 * 1000;

    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, trigger, pi);
    else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, trigger, pi);
    else
        alarmManager.set(AlarmManager.RTC_WAKEUP, trigger, pi);
    Log.i(TAG, "Start daily job next=" + SimpleDateFormat.getDateTimeInstance().format(trigger));
}
 
Example 9
Source File: TasksUtils.java    From FreezeYou with Apache License 2.0 5 votes vote down vote up
private static void setRealTimeTask(AlarmManager alarmManager, long triggerAtMillis, PendingIntent operation) {
    if (Build.VERSION.SDK_INT >= 23) {
        alarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, operation);
    } else if (Build.VERSION.SDK_INT >= 19) {
        alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, operation);
    } else {
        alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, operation);
    }
}
 
Example 10
Source File: BackgroundService.java    From BackPackTrackII with GNU General Public License v3.0 5 votes vote down vote up
public static void startWeatherUpdates(Context context) {
    // Check if weather updates enabled
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    if (prefs.getBoolean(SettingsFragment.PREF_PRIVACY, SettingsFragment.DEFAULT_PRIVACY)) {
        Log.i(TAG, "Weather updates: privacy mode");
        return;
    }
    if (!prefs.getBoolean(SettingsFragment.PREF_WEATHER_ENABLED, SettingsFragment.DEFAULT_WEATHER_ENABLED)) {
        Log.i(TAG, "Weather updates disabled");
        return;
    }

    // Display last weather report
    String report = prefs.getString(SettingsFragment.PREF_LAST_WEATHER_REPORT, null);
    Weather weather = (report == null ? null : Weather.deserialize(report));
    if (weather != null && weather.isValid(context))
        showWeatherNotification(weather, context);

    // Set alarm
    Intent alarmIntent = new Intent(context, BackgroundService.class);
    alarmIntent.setAction(BackgroundService.ACTION_UPDATE_WEATHER);
    PendingIntent pi = PendingIntent.getService(context, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    int interval = Integer.parseInt(prefs.getString(SettingsFragment.PREF_WEATHER_INTERVAL, SettingsFragment.DEFAULT_WEATHER_INTERVAL));
    int ms = 60 * 1000 * interval;
    long trigger = new Date().getTime() / ms * ms + ms;
    boolean wakeup = prefs.getBoolean(SettingsFragment.PREF_WEATHER_WAKEUP, SettingsFragment.DEFAULT_WEATHER_WAKEUP);
    if (wakeup && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        // https://code.google.com/p/android-developer-preview/issues/detail?id=2233
        // https://code.google.com/p/android-developer-preview/issues/detail?id=2225
        am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, trigger, pi);
    else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
        am.setExact(AlarmManager.RTC_WAKEUP, trigger, pi);
    else
        am.set(AlarmManager.RTC_WAKEUP, trigger, pi);
    Log.i(TAG, "Start weather updates interval=" + interval + "m" + " next=" + SimpleDateFormat.getDateTimeInstance().format(trigger) + " wakeup=" + wakeup);
}
 
Example 11
Source File: TimeTask.java    From TimeTask with Apache License 2.0 5 votes vote down vote up
/**
 * 装在定时任务
 * @param Time
 */
private void configureAlarmManager(long Time) {
    AlarmManager manager = (AlarmManager) mContext.getSystemService(ALARM_SERVICE);
    PendingIntent pendIntent = getPendingIntent();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, Time, pendIntent);
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        manager.setExact(AlarmManager.RTC_WAKEUP, Time, pendIntent);
    } else {
        manager.set(AlarmManager.RTC_WAKEUP, Time, pendIntent);
    }
}
 
Example 12
Source File: Notifications.java    From xDrip-plus 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 ) {
        Log.e("Notifications" , "ArmTimer recieved a negative time, will fire in 6 minutes");
        wakeTime = now + 6 * 60000;
    } else if  (wakeTime >=  now + 6 * 60000) {
    	 Log.i("Notifications" , "ArmTimer recieved a bigger time, will fire in 6 minutes");
         wakeTime = now + 6 * 60000;
    }  else if (wakeTime == now) {
        Log.e("Notifications", "should arm right now, waiting one more second to avoid infinitue loop");
        wakeTime = now + 1000;
    }
    
    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.M) {
        alarm.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, wakeTime, 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 13
Source File: McsService.java    From android_packages_apps_GmsCore with Apache License 2.0 5 votes vote down vote up
public static void scheduleReconnect(Context context) {
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
    long delay = getCurrentDelay();
    logd("Scheduling reconnect in " + delay / 1000 + " seconds...");
    PendingIntent pi = PendingIntent.getBroadcast(context, 1, new Intent(ACTION_RECONNECT, null, context, TriggerReceiver.class), 0);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        alarmManager.setExactAndAllowWhileIdle(ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + delay, pi);
    } else {
        alarmManager.set(ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + delay, pi);
    }
}
 
Example 14
Source File: NotificationUtilites.java    From GotoSleep with GNU General Public License v3.0 5 votes vote down vote up
public static void setNotifications(boolean nextDay, boolean notificationsEnabled, int[] bedtime, int notificationDelay, int numNotifications, Context context) {
    if (notificationsEnabled) {
        Calendar bedtimeCalendar = getBedtimeCal(bedtime);


        if (nextDay){
            bedtimeCalendar.setTimeInMillis(bedtimeCalendar.getTimeInMillis() + ONE_DAY_MILLIS);
        } else if (bedtimeCalendar.getTimeInMillis() < System.currentTimeMillis()){
            bedtimeCalendar.setTimeInMillis(bedtimeCalendar.getTimeInMillis() + ONE_DAY_MILLIS);
        }

        int errorMargin = 30;
        if (PreferenceManager.getDefaultSharedPreferences(context).getInt(CURRENT_NOTIFICATION_KEY, 1) != 1){
            if (abs(System.currentTimeMillis() - bedtimeCalendar.getTimeInMillis()) > ((notificationDelay * numNotifications + errorMargin) * 60000 )){
                PreferenceManager.getDefaultSharedPreferences(context).edit().putInt(CURRENT_NOTIFICATION_KEY, 1).apply();
            }
        }

        Intent intent1 = new Intent(context, BedtimeNotificationReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
                FIRST_NOTIFICATION_ALARM_REQUEST_CODE, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager am = (AlarmManager) context.getSystemService(ALARM_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, bedtimeCalendar.getTimeInMillis(), pendingIntent);
        } else {
            am.setExact(AlarmManager.RTC_WAKEUP, bedtimeCalendar.getTimeInMillis(), pendingIntent);
        }
    }
}
 
Example 15
Source File: BedtimeNotificationHelper.java    From GotoSleep with GNU General Public License v3.0 5 votes vote down vote up
private void setBedtimeNotification(Context context, Calendar bedtime){
    Intent intent1 = new Intent(context, BedtimeNotificationReceiver.class);

    PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
            FIRST_NOTIFICATION_ALARM_REQUEST_CODE, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager am = (AlarmManager) context.getSystemService(ALARM_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, bedtime.getTimeInMillis(), pendingIntent);
    } else {
        am.setExact(AlarmManager.RTC_WAKEUP, bedtime.getTimeInMillis(), pendingIntent);
    }


}
 
Example 16
Source File: AlarmScheduler.java    From X-Alarm with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Set Alarm via AlarmManager
 *
 * Beginning with API 19 (KITKAT) alarm delivery is inexact: the OS will shift
 * alarms in order to minimize wakeups and battery use. There are new APIs to
 * support applications which need strict delivery guarantees
 *
 * @param context
 * @param time
 * @param pendingIntent
 */
private static void setAlarm(Context context, long time, PendingIntent pendingIntent) {
    AlarmManager alarmManager =
            (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, time, pendingIntent);
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, time, pendingIntent);
    } else {
        alarmManager.set(AlarmManager.RTC_WAKEUP, time, pendingIntent);
    }
}
 
Example 17
Source File: G5CollectionService.java    From xDrip-Experimental with GNU General Public License v3.0 5 votes vote down vote up
public void keepAlive() {
    long wakeTime = getNextAdvertiseTime() - 60*1000;
    //Log.e(TAG, "Delay Time: " + minuteDelay);
    Log.e(TAG, "OnStart Wake Time: " + wakeTime);
    AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
    if (pendingIntent != null)
        alarm.cancel(pendingIntent);
    pendingIntent = PendingIntent.getService(this, 0, new Intent(this, this.getClass()), 0);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        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);
}
 
Example 18
Source File: Notifications.java    From xDrip 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 ) {
        Log.e("Notifications" , "ArmTimer recieved a negative time, will fire in 6 minutes");
        wakeTime = now + 6 * 60000;
    } else if  (wakeTime >=  now + 6 * 60000) {
    	 Log.i("Notifications" , "ArmTimer recieved a bigger time, will fire in 6 minutes");
         wakeTime = now + 6 * 60000;
    }  else if (wakeTime == now) {
        Log.e("Notifications", "should arm right now, waiting one more second to avoid infinitue loop");
        wakeTime = now + 1000;
    }
    
    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.M) {
        alarm.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, wakeTime, 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 19
Source File: EventPreferencesNFC.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("EventPreferencesNFC.setAlarm", "endTime=" + result);
            }*/

            /*if (ApplicationPreferences.applicationUseAlarmClock(context)) {
                //Intent intent = new Intent(context, NFCEventEndBroadcastReceiver.class);
                Intent intent = new Intent();
                intent.setAction(PhoneProfilesService.ACTION_NFC_EVENT_END_BROADCAST_RECEIVER);
                //intent.setClass(context, NFCEventEndBroadcastReceiver.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("EventPreferencesNFC.setAlarm", "elapsedTime=" + hours + ":" + minutes + ":" + seconds);
                }

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

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

            //Intent intent = new Intent(context, NFCEventEndBroadcastReceiver.class);
            Intent intent = new Intent();
            intent.setAction(PhoneProfilesService.ACTION_NFC_EVENT_END_BROADCAST_RECEIVER);
            //intent.setClass(context, NFCEventEndBroadcastReceiver.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 20
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);
                }
            }
        }
    }
}