Example usage for android.app AlarmManager RTC_WAKEUP

List of usage examples for android.app AlarmManager RTC_WAKEUP

Introduction

In this page you can find the example usage for android.app AlarmManager RTC_WAKEUP.

Prototype

int RTC_WAKEUP

To view the source code for android.app AlarmManager RTC_WAKEUP.

Click Source Link

Document

Alarm time in System#currentTimeMillis System.currentTimeMillis() (wall clock time in UTC), which will wake up the device when it goes off.

Usage

From source file:com.prod.intelligent7.engineautostart.ConnectDaemonService.java

void setRecurringBootAlarm(long on_time, long idle_interval) {
    if (recurringBootIntent != null) {
        alarmManager.cancel(recurringBootIntent);
        //return;
    }/* www. j ava2s.  co m*/
    recurringBootIntent = null;
    GregorianCalendar gToday = new GregorianCalendar(
            TimeZone.getTimeZone(getResources().getString(R.string.my_time_zone_en)));
    if (gToday.get(Calendar.HOUR_OF_DAY) >= 7 && gToday.get(Calendar.HOUR_OF_DAY) < 21)
        return;
    long total_wait = idle_interval;//on_time+idle_interval;
    String bootParameter = "" + on_time + "-" + idle_interval;
    Intent jIntent = new Intent(this, ConnectDaemonService.class);
    //M1-00 (cool) or M1-01 (warm)
    jIntent.setAction(ALARM_NBOOT);
    jIntent.putExtra(ConnectDaemonService.ALARM_DONE, ALARM_NBOOT);
    jIntent.putExtra(ConnectDaemonService.ALARM_NBOOT, bootParameter);
    recurringBootIntent = PendingIntent.getService(this, ++nBootAlarmRequestId % 100 + 300, jIntent,
            PendingIntent.FLAG_ONE_SHOT);
    alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + total_wait, recurringBootIntent);
    Log.i("ALARM_SET", "to start recurring boot in " + total_wait / 60000);
    //startScheduledJobs();
}

From source file:com.pacoapp.paco.triggering.NotificationCreator.java

@SuppressLint("NewApi")
private void createAlarmToCancelNotificationAtTimeout(Context context, NotificationHolder notificationHolder) {
    DateTime alarmTime = new DateTime(notificationHolder.getAlarmTime());
    int timeoutMinutes = (int) (notificationHolder.getTimeoutMillis() / MILLIS_IN_MINUTE);
    DateTime timeoutTime = new DateTime(alarmTime).plusMinutes(timeoutMinutes);
    long elapsedDurationInMillis = timeoutTime.getMillis();

    Log.info("Creating cancel alarm to timeout notification for holder: " + notificationHolder.getId()
            + ". experiment = " + notificationHolder.getExperimentId() + ". alarmtime = "
            + new DateTime(alarmTime).toString() + " timing out in " + timeoutMinutes + " minutes");

    Intent ultimateIntent = new Intent(context, AlarmReceiver.class);
    Uri uri = Uri.withAppendedPath(NotificationHolderColumns.CONTENT_URI,
            notificationHolder.getId().toString());
    ultimateIntent.setData(uri);//from ww w . ja v a2  s  .  com
    ultimateIntent.putExtra(NOTIFICATION_ID, notificationHolder.getId().longValue());

    PendingIntent intent = PendingIntent.getBroadcast(context.getApplicationContext(), 2, ultimateIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmManager.cancel(intent);
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, elapsedDurationInMillis, intent);
    } else {
        alarmManager.set(AlarmManager.RTC_WAKEUP, elapsedDurationInMillis, intent);
    }

}

From source file:com.prod.intelligent7.engineautostart.ConnectDaemonService.java

void startHourlyCheckAlarm() {
    if (scheduleAlarm != null) {
        alarmManager.cancel(scheduleAlarm);
        //return;
    }//  w w  w.  ja  v  a 2  s.  com
    Intent jIntent = new Intent(this, ConnectDaemonService.class);
    //M1-00 (cool) or M1-01 (warm)
    jIntent.putExtra(ConnectDaemonService.ALARM_DONE, ALARM_HOUR);
    jIntent.setAction(ALARM_HOUR);
    scheduleAlarm = PendingIntent.getService(this, ++alarmRequestId % 100 + 500, jIntent,
            PendingIntent.FLAG_ONE_SHOT);
    alarmManager.set(AlarmManager.RTC_WAKEUP, 1 * 60 * 60 * 1000 + System.currentTimeMillis(), scheduleAlarm);
    Log.i("ALARM_SET", "restart check alarm set for 1 hour");
    //startScheduledJobs();
}

From source file:org.gnucash.android.ui.transaction.TransactionFormFragment.java

/**
 * Collects information from the fragment views and uses it to create 
 * and save a transaction/*from  w  ww.  j  a  v a2s.c o m*/
 */
private void saveNewTransaction() {
    Calendar cal = new GregorianCalendar(mDate.get(Calendar.YEAR), mDate.get(Calendar.MONTH),
            mDate.get(Calendar.DAY_OF_MONTH), mTime.get(Calendar.HOUR_OF_DAY), mTime.get(Calendar.MINUTE),
            mTime.get(Calendar.SECOND));
    String name = mNameEditText.getText().toString();
    String description = mDescriptionEditText.getText().toString();
    BigDecimal amountBigd = parseInputToDecimal(mAmountEditText.getText().toString());

    long accountID = ((TransactionsActivity) getSherlockActivity()).getCurrentAccountID();
    Currency currency = Currency.getInstance(mTransactionsDbAdapter.getCurrencyCode(accountID));
    Money amount = new Money(amountBigd, currency);
    TransactionType type;
    if (mAccountType.hasDebitNormalBalance()) {
        type = amount.isNegative() ? TransactionType.CREDIT : TransactionType.DEBIT;
    } else
        type = amount.isNegative() ? TransactionType.DEBIT : TransactionType.CREDIT;
    if (mTransaction != null) {
        mTransaction.setAmount(amount);
        mTransaction.setName(name);
        mTransaction.setTransactionType(type);
    } else {
        mTransaction = new Transaction(amount, name, type);
    }

    mTransaction.setAccountUID(mTransactionsDbAdapter.getAccountUID(accountID));
    mTransaction.setTime(cal.getTimeInMillis());
    mTransaction.setDescription(description);

    //set the double account
    if (mUseDoubleEntry) {
        long doubleAccountId = mDoubleAccountSpinner.getSelectedItemId();
        //negate the transaction before saving if we are in the double account
        if (isInDoubleAccount()) {
            mTransaction.setAmount(amount.negate());
            mTransaction.setAccountUID(mTransactionsDbAdapter.getAccountUID(doubleAccountId));
            mTransaction.setDoubleEntryAccountUID(mTransactionsDbAdapter.getAccountUID(accountID));
        } else {
            mTransaction.setAccountUID(mTransactionsDbAdapter.getAccountUID(accountID));
            mTransaction.setDoubleEntryAccountUID(mTransactionsDbAdapter.getAccountUID(doubleAccountId));
        }
    }
    //save the normal transaction first
    mTransactionsDbAdapter.addTransaction(mTransaction);

    //set up recurring transaction if requested
    int recurrenceIndex = mRecurringTransactionSpinner.getSelectedItemPosition();
    if (recurrenceIndex != 0) {
        String[] recurrenceOptions = getResources().getStringArray(R.array.recurrence_period_millis);
        long recurrencePeriodMillis = Long.parseLong(recurrenceOptions[recurrenceIndex]);
        long firstRunMillis = System.currentTimeMillis() + recurrencePeriodMillis;

        Transaction recurringTransaction = new Transaction(mTransaction, true);
        recurringTransaction.setRecurrencePeriod(recurrencePeriodMillis);
        long recurringTransactionId = mTransactionsDbAdapter.addTransaction(recurringTransaction);

        PendingIntent recurringPendingIntent = PendingIntent.getBroadcast(getActivity().getApplicationContext(),
                (int) recurringTransactionId, Transaction.createIntent(mTransaction),
                PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, firstRunMillis, recurrencePeriodMillis,
                recurringPendingIntent);
    }

    //update widgets, if any
    WidgetConfigurationActivity.updateAllWidgets(getActivity().getApplicationContext());

    finish();
}

From source file:xyz.lebalex.lockscreen.MainActivity.java

private void startBackgroundService(int interval, int startTime) {
    try {/*  w ww.ja  v a2  s . c o m*/
        Intent alarmIntent = new Intent(this, LockScreenServiceReceiver.class);
        alarmIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
        PendingIntent pendingIntent;
        pendingIntent = PendingIntent.getBroadcast(this, 1001, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

        if (interval > 0) {
            Calendar curentTime = Calendar.getInstance();

            Calendar startCalen = Calendar.getInstance();
            startCalen.set(Calendar.HOUR_OF_DAY, startTime);
            startCalen.set(Calendar.MINUTE, 5);
            startCalen.set(Calendar.SECOND, 0);
            startCalen.set(Calendar.MILLISECOND, 0);

            boolean find = false;
            while (!find) {
                if (curentTime.before(startCalen))
                    find = true;
                else
                    startCalen.add(Calendar.MILLISECOND, interval);
            }

            //manager.setRepeating(AlarmManager.RTC_WAKEUP, startCalen.getTimeInMillis(), interval, pendingIntent);
            manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, startCalen.getTimeInMillis(),
                    pendingIntent);

            SharedPreferences.Editor editor = sp.edit();
            editor.putBoolean("start_service", true);
            editor.commit();
            LogWrite.Log(this,
                    "start Alarm " + startCalen.get(Calendar.YEAR) + "-" + startCalen.get(Calendar.MONTH) + "-"
                            + startCalen.get(Calendar.DATE) + " " + startCalen.get(Calendar.HOUR_OF_DAY) + ":"
                            + startCalen.get(Calendar.MINUTE) + ":" + startCalen.get(Calendar.SECOND));
        } else {
            LogWrite.Log(this, "stop Alarm");
        }
    } catch (Exception e) {
        LogWrite.LogError(this, e.getMessage());
    }
}

From source file:com.googlecode.mindbell.accessors.ContextAccessor.java

/**
 * Reschedule the bell by letting AlarmManager send an intent to Scheduler.
 *
 * @param nextTargetTimeMillis/*from   w ww . j  a va 2s.  co  m*/
 *         Millis to be given to Scheduler as now (or nextTargetTimeMillis from the perspective of the previous call)
 * @param nextMeditationPeriod
 *         null if not meditating, otherwise 0: ramp-up, 1-(n-1): intermediate period, n: last period, n+1: beyond end
 */
public void reschedule(long nextTargetTimeMillis, Integer nextMeditationPeriod) {
    PendingIntent sender = createSchedulerBroadcastIntent(true, nextTargetTimeMillis, nextMeditationPeriod);
    AlarmManagerCompat alarmManager = new AlarmManagerCompat(context);
    alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, nextTargetTimeMillis, sender);
    TimeOfDay nextBellTime = new TimeOfDay(nextTargetTimeMillis);
    Log.d(TAG, "Scheduled next bell alarm for " + nextBellTime.getLogString());
}

From source file:com.prod.intelligent7.engineautostart.ConnectDaemonService.java

void startScheduleAlarm() {
    if (scheduleAlarm != null) {
        alarmManager.cancel(scheduleAlarm);
        //return;
    }/*from  w  w w.  j ava  2  s  . c  o m*/
    Intent jIntent = new Intent(this, ConnectDaemonService.class);
    //M1-00 (cool) or M1-01 (warm)
    jIntent.putExtra(ConnectDaemonService.ALARM_DONE, ALARM_DONE);
    scheduleAlarm = PendingIntent.getService(this, ++alarmRequestId, jIntent, PendingIntent.FLAG_ONE_SHOT);
    alarmManager.set(AlarmManager.RTC_WAKEUP, 1 * 60 * 60 * 1000 + System.currentTimeMillis(), scheduleAlarm);
    Log.i("ALARM_SET", "restart new alarm set for 1 hour");
    startScheduledJobs();
}

From source file:org.metawatch.manager.Monitors.java

static void startAlarmTicker(Context context) {
    if (Preferences.logging)
        Log.d(MetaWatch.TAG, "startAlarmTicker()");
    alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    intent = new Intent(context, AlarmReceiver.class);
    intent.putExtra("action_update", "update");
    sender = PendingIntent.getBroadcast(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, 0, AlarmManager.INTERVAL_HALF_HOUR, sender);
}

From source file:com.mobilyzer.MeasurementScheduler.java

public synchronized String submitTask(MeasurementTask newTask) {
    // TODO check if scheduler is running...
    // and there is a current running/scheduled task
    String newTaskId = newTask.getTaskId();
    tasksStatus.put(newTaskId, TaskStatus.SCHEDULED);
    idToClientKey.put(newTaskId, newTask.getKey());
    Logger.d("MeasurementScheduler --> submitTask: " + newTask.getDescription().key + " " + newTaskId);
    MeasurementTask current;//from   w ww . j  a  va 2 s.  c  o  m
    if (getCurrentTask() != null) {
        current = getCurrentTask();
        Logger.d("submitTask: current is NOT null");
    } else {
        current = null;
        Logger.d("submitTask: current is null");
    }
    // preemption condition
    if (current != null && newTask.getDescription().priority < current.getDescription().priority
            && new Date(current.getDuration() + getCurrentTaskStartTime().getTime())
                    .after(newTask.getDescription().endTime)) {
        Logger.d("submitTask: trying to cancel/preempt the task");
        // finding the current instance in pending tasks. we can call
        // pause on that instance only
        if (pendingTasks.containsKey(current)) {
            for (MeasurementTask mt : pendingTasks.keySet()) {
                if (current.equals(mt)) {
                    current = mt;
                    break;
                }
            }
            Logger.e("Cancelling Current Task");
            if (current instanceof PreemptibleMeasurementTask
                    && ((PreemptibleMeasurementTask) current).pause()) {
                pendingTasks.remove(current);
                ((PreemptibleMeasurementTask) current).updateTotalRunningTime(
                        System.currentTimeMillis() - getCurrentTaskStartTime().getTime());
                if (newTask.timeFromExecution() <= 0) {
                    mainQueue.add(newTask);
                    mainQueue.add(current);
                    handleMeasurement();
                } else {
                    mainQueue.add(newTask);
                    mainQueue.add(current);
                    long timeFromExecution = newTask.timeFromExecution();
                    measurementIntentSender = PendingIntent.getBroadcast(this, 0,
                            new UpdateIntent(UpdateIntent.MEASUREMENT_ACTION),
                            PendingIntent.FLAG_CANCEL_CURRENT);
                    alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + timeFromExecution,
                            measurementIntentSender);
                    setCurrentTask(newTask);
                    setCurrentTaskStartTime(new Date(System.currentTimeMillis() + timeFromExecution));
                }

            } else if (current.stop()) {
                pendingTasks.remove(current);
                if (newTask.timeFromExecution() <= 0) {
                    mainQueue.add(newTask);
                    mainQueue.add(current);
                    handleMeasurement();
                } else {
                    mainQueue.add(newTask);
                    mainQueue.add(current);
                    long timeFromExecution = newTask.timeFromExecution();
                    measurementIntentSender = PendingIntent.getBroadcast(this, 0,
                            new UpdateIntent(UpdateIntent.MEASUREMENT_ACTION),
                            PendingIntent.FLAG_CANCEL_CURRENT);
                    alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + timeFromExecution,
                            measurementIntentSender);
                    // setCurrentTask(null);
                    setCurrentTask(newTask);
                    setCurrentTaskStartTime(new Date(System.currentTimeMillis() + timeFromExecution));
                }
            } else {
                mainQueue.add(newTask);
            }
        } else {
            alarmManager.cancel(measurementIntentSender);
            if (newTask.timeFromExecution() <= 0) {
                mainQueue.add(newTask);
                handleMeasurement();
            } else {
                mainQueue.add(newTask);
                long timeFromExecution = newTask.timeFromExecution();
                measurementIntentSender = PendingIntent.getBroadcast(this, 0,
                        new UpdateIntent(UpdateIntent.MEASUREMENT_ACTION), PendingIntent.FLAG_CANCEL_CURRENT);
                alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + timeFromExecution,
                        measurementIntentSender);
                // setCurrentTask(null);
                setCurrentTask(newTask);
                setCurrentTaskStartTime(new Date(System.currentTimeMillis() + timeFromExecution));
            }
        }
    } else {
        Logger.d("submitTask: adding to mainqueue");
        mainQueue.add(newTask);
        if (current == null) {
            Logger.d("submitTask: adding to mainqueue, current is null");
            Logger.d("submitTask: calling handleMeasurement");
            alarmManager.cancel(measurementIntentSender);
            handleMeasurement();
        } else {
            Logger.d("submitTask: adding to mainqueue, current is not null: " + current.getMeasurementType()
                    + " " + getCurrentTaskStartTime());
            if (pendingTasks.containsKey(current)) {
                Logger.d("submitTask: isDone?" + pendingTasks.get(current).isDone());
                if (pendingTasks.get(current).isDone()) {
                    alarmManager.cancel(measurementIntentSender);
                    alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 3 * 1000,
                            measurementIntentSender);
                } else if (getCurrentTaskStartTime() != null) {
                    if (!current.getMeasurementType().equals(RRCTask.TYPE)
                            && new Date(System.currentTimeMillis() - Config.MAX_TASK_DURATION)
                                    .after(getCurrentTaskStartTime())) {
                        Logger.d("submitTask: 1");
                        pendingTasks.get(current).cancel(true);
                        handleMeasurement();

                    } else if (current.getMeasurementType().equals(RRCTask.TYPE) && new Date(
                            System.currentTimeMillis() - (Config.DEFAULT_RRC_TASK_DURATION + 15 * 60 * 1000))
                                    .after(getCurrentTaskStartTime())) {
                        Logger.d("submitTask: 2");
                        pendingTasks.get(current).cancel(true);
                        handleMeasurement();
                    } else {
                        Logger.d("submitTask: 3");
                        alarmManager.set(AlarmManager.RTC_WAKEUP,
                                System.currentTimeMillis() + Config.MAX_TASK_DURATION / 2,
                                measurementIntentSender);
                    }
                }

            } else {
                Logger.d("submitTask: not found in pending task");
                handleMeasurement();
            }

        }
    }
    return newTaskId;
}

From source file:org.voidsink.anewjkuapp.utils.AppUtils.java

public static void updateSyncAlarm(Context context, boolean reCreateAlarm) {
    boolean mIsCalendarSyncEnabled = false;
    boolean mIsKusssSyncEnable = false;
    boolean mIsMasterSyncEnabled = ContentResolver.getMasterSyncAutomatically();

    if (mIsMasterSyncEnabled) {
        final Account mAccount = getAccount(context);
        if (mAccount != null) {
            mIsCalendarSyncEnabled = ContentResolver.getSyncAutomatically(mAccount,
                    CalendarContractWrapper.AUTHORITY());
            mIsKusssSyncEnable = ContentResolver.getSyncAutomatically(mAccount, KusssContentContract.AUTHORITY);
        }/*from  ww w.  j a  v a 2 s  . c o m*/
    }

    Log.d(TAG, String.format("MasterSync=%b, CalendarSync=%b, KusssSync=%b", mIsMasterSyncEnabled,
            mIsCalendarSyncEnabled, mIsKusssSyncEnable));

    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, SyncAlarmService.class);
    intent.putExtra(Consts.ARG_UPDATE_CAL, !mIsCalendarSyncEnabled);
    intent.putExtra(Consts.ARG_UPDATE_KUSSS, !mIsKusssSyncEnable);
    intent.putExtra(Consts.ARG_RECREATE_SYNC_ALARM, true);
    intent.putExtra(Consts.SYNC_SHOW_PROGRESS, true);

    // check if pending intent exists
    reCreateAlarm = reCreateAlarm
            || (PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_NO_CREATE) == null);

    // new pending intent
    PendingIntent alarmIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    if (!mIsMasterSyncEnabled || !mIsCalendarSyncEnabled || !mIsKusssSyncEnable) {
        if (reCreateAlarm) {
            long interval = PreferenceWrapper.getSyncInterval(context) * DateUtils.HOUR_IN_MILLIS;

            // synchronize in half an hour
            am.setInexactRepeating(AlarmManager.RTC_WAKEUP,
                    System.currentTimeMillis() + AlarmManager.INTERVAL_HALF_HOUR, interval, alarmIntent);
        }
    } else {
        am.cancel(alarmIntent);
    }
}