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.mobiperf.MeasurementScheduler.java

/** Set the interval for checkin in seconds */
public synchronized void setCheckinInterval(long interval) {
    this.checkinIntervalSec = Math.max(Config.MIN_CHECKIN_INTERVAL_SEC, interval);
    // the new checkin schedule will start in PAUSE_BETWEEN_CHECKIN_CHANGE_MSEC seconds
    checkinIntentSender = PendingIntent.getBroadcast(this, 0, new UpdateIntent("", UpdateIntent.CHECKIN_ACTION),
            PendingIntent.FLAG_CANCEL_CURRENT);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
            System.currentTimeMillis() + Config.PAUSE_BETWEEN_CHECKIN_CHANGE_MSEC, checkinIntervalSec * 1000,
            checkinIntentSender);//from   w  ww.jav  a 2  s.  co  m

    Logger.i("Setting checkin interval to " + interval + " seconds");
}

From source file:com.matthewmitchell.peercoin_android_wallet.WalletApplication.java

public void scheduleStartBlockchainService() {

    final WalletApplication wa = this;

    this.setOnLoadedCallback(new Runnable() {

        @Override//from  www. j a v a  2 s . c  o  m
        public void run() {

            final long lastUsedAgo = config.getLastUsedAgo();

            // apply some backoff
            final long alarmInterval;
            if (lastUsedAgo < Constants.LAST_USAGE_THRESHOLD_JUST_MS)
                alarmInterval = AlarmManager.INTERVAL_FIFTEEN_MINUTES;
            else if (lastUsedAgo < Constants.LAST_USAGE_THRESHOLD_RECENTLY_MS)
                alarmInterval = AlarmManager.INTERVAL_HALF_DAY;
            else
                alarmInterval = AlarmManager.INTERVAL_DAY;

            log.info("last used {} minutes ago, rescheduling blockchain sync in roughly {} minutes",
                    lastUsedAgo / DateUtils.MINUTE_IN_MILLIS, alarmInterval / DateUtils.MINUTE_IN_MILLIS);
            assertTrue(config != null);
            final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            final PendingIntent alarmIntent = PendingIntent.getService(wa, 0,
                    new Intent(wa, BlockchainServiceImpl.class), 0);
            alarmManager.cancel(alarmIntent);

            // workaround for no inexact set() before KitKat
            final long now = System.currentTimeMillis();
            alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, now + alarmInterval,
                    AlarmManager.INTERVAL_DAY, alarmIntent);

        }

    });

}

From source file:me.cpwc.nibblegram.android.NotificationsController.java

private void scheduleNotificationRepeat() {
    try {/*ww w  .ja va2 s .  c  o m*/
        AlarmManager alarm = (AlarmManager) ApplicationLoader.applicationContext
                .getSystemService(Context.ALARM_SERVICE);
        PendingIntent pintent = PendingIntent.getService(ApplicationLoader.applicationContext, 0,
                new Intent(ApplicationLoader.applicationContext, NotificationRepeat.class), 0);
        SharedPreferences preferences = ApplicationLoader.applicationContext
                .getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
        int minutes = preferences.getInt("repeat_messages", 60);
        if (minutes > 0 && personal_count > 0) {
            alarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + minutes * 60 * 1000, pintent);
        } else {
            alarm.cancel(pintent);
        }
    } catch (Exception e) {
        FileLog.e("tmessages", e);
    }
}

From source file:com.mobilyzer.MeasurementScheduler.java

private synchronized void handleMeasurement() {
    alarmManager.cancel(measurementIntentSender);
    setCurrentTask(null);/* w  ww. j  a  va  2  s .com*/
    try {
        Logger.d("MeasurementScheduler -> In handleMeasurement " + mainQueue.size() + " "
                + waitingTasksQueue.size());
        MeasurementTask task = mainQueue.peek();
        // update the waiting queue. It contains all the tasks that are ready
        // to be executed. Here we extract all those ready tasks from main queue
        while (task != null && task.timeFromExecution() <= 0) {
            mainQueue.poll();

            if (task.getDescription().getType().equals(RRCTask.TYPE)
                    && phoneUtils.getNetwork().equals(PhoneUtils.NETWORK_WIFI)) {
                long updatedStartTime = System.currentTimeMillis() + (long) (10 * 60 * 1000);
                task.getDescription().startTime.setTime(updatedStartTime);
                mainQueue.add(task);
                Logger.i("MeasurementScheduler: handleMeasurement: delaying RRC task on "
                        + phoneUtils.getNetwork());
                task = mainQueue.peek();
                continue;
            }
            Logger.i("MeasurementScheduler: handleMeasurement: " + task.getDescription().key + " "
                    + task.getDescription().type + " added to waiting list");
            waitingTasksQueue.add(task);
            task = mainQueue.peek();
        }

        if (!phoneUtils.isNetworkAvailable()) {
            Logger.i("No connection is available, set an alarm for 5 min");
            measurementIntentSender = PendingIntent.getBroadcast(this, 0,
                    new UpdateIntent(UpdateIntent.MEASUREMENT_ACTION), PendingIntent.FLAG_CANCEL_CURRENT);
            alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5 * 60 * 1000),
                    measurementIntentSender);
            return;
        }

        if (waitingTasksQueue.size() != 0) {
            Logger.i("waiting list size is " + waitingTasksQueue.size());
            MeasurementTask ready = waitingTasksQueue.poll();
            Logger.i("ready: " + ready.getDescription().getType());

            MeasurementDesc desc = ready.getDescription();
            long newStartTime = desc.startTime.getTime() + (long) desc.intervalSec * 1000;

            if (desc.count == MeasurementTask.INFINITE_COUNT
                    && desc.priority != MeasurementTask.USER_PRIORITY) {
                if (serverTasks.containsKey(desc.toString())
                        && serverTasks.get(desc.toString()).after(desc.endTime)) {
                    ready.getDescription().endTime.setTime(serverTasks.get(desc.toString()).getTime());
                }
            }

            /**
             * Add a clone of the task if it's still valid it does not change the taskID (hashCode)
             */
            if (newStartTime < ready.getDescription().endTime.getTime()
                    && (desc.count == MeasurementTask.INFINITE_COUNT || desc.count > 1)) {
                MeasurementTask newTask = ready.clone();
                if (desc.count != MeasurementTask.INFINITE_COUNT) {
                    newTask.getDescription().count--;
                }
                newTask.getDescription().startTime.setTime(newStartTime);
                tasksStatus.put(newTask.getTaskId(), TaskStatus.SCHEDULED);
                mainQueue.add(newTask);
            } else {
                if (desc.priority != MeasurementTask.USER_PRIORITY) {
                    serverTasks.remove(desc.toString());
                }
            }

            if (ready.getDescription().endTime.before(new Date())) {
                Intent intent = new Intent();
                intent.setAction(UpdateIntent.MEASUREMENT_PROGRESS_UPDATE_ACTION);
                intent.putExtra(UpdateIntent.TASK_STATUS_PAYLOAD, Config.TASK_CANCELED);
                MeasurementResult[] tempResults = MeasurementResult.getFailureResult(ready,
                        new CancellationException("Task cancelled!"));
                intent.putExtra(UpdateIntent.RESULT_PAYLOAD, tempResults);
                intent.putExtra(UpdateIntent.TASKID_PAYLOAD, ready.getTaskId());
                intent.putExtra(UpdateIntent.CLIENTKEY_PAYLOAD, ready.getKey());
                MeasurementScheduler.this.sendBroadcast(intent);

                if (desc.priority != MeasurementTask.USER_PRIORITY) {
                    serverTasks.remove(desc.toString());
                }

                handleMeasurement();
            } else {
                Logger.d("MeasurementScheduler -> " + ready.getDescription().getType() + " is gonna run");
                Future<MeasurementResult[]> future;
                setCurrentTask(ready);
                setCurrentTaskStartTime(Calendar.getInstance().getTime());
                if (ready.getDescription().priority == MeasurementTask.USER_PRIORITY) {
                    // User task can override the power policy. So a different task wrapper is used.
                    future = measurementExecutor.submit(new UserMeasurementTask(ready, this));
                } else {
                    future = measurementExecutor
                            .submit(new ServerMeasurementTask(ready, this, resourceCapManager));
                }

                synchronized (pendingTasks) {
                    pendingTasks.put(ready, future);
                }
            }
        } else {// if(task.timeFromExecution()>0){
            MeasurementTask waiting = mainQueue.peek();
            if (waiting != null) {
                long timeFromExecution = task.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);// TODO
                setCurrentTaskStartTime(null);
            }

        }
    } catch (IllegalArgumentException e) {
        // Task creation in clone can create this exception

    } catch (Exception e) {
        // We don't want any unexpected exception to crash the process
    }
}

From source file:org.thoughtcrime.SMP.notifications.MessageNotifier.java

private static void scheduleReminder(Context context, MasterSecret masterSecret, int count) {
    if (count >= TextSecurePreferences.getRepeatAlertsCount(context)) {
        return;//  w  w w .  j  a va 2  s .co m
    }

    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent alarmIntent = new Intent(ReminderReceiver.REMINDER_ACTION);
    alarmIntent.putExtra("reminder_count", count);

    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);
    long timeout = TimeUnit.MINUTES.toMillis(2);

    alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + timeout, pendingIntent);
}

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

void startOneBootAlarm() {
    if (oneBootIntent != null) {
        alarmManager.cancel(oneBootIntent);
        //return;
    }/*from w w  w  .jav  a 2s.  c  o  m*/
    oneBootIntent = null;
    String bootParameter = readBootParameter(1);
    Log.i("ALARM_SET", "got 1 boot parameters " + (bootParameter == null ? "nothing" : bootParameter));
    if (bootParameter == null)
        return;
    int idx = bootParameter.indexOf("-");
    if (idx < 0)
        return;
    long init_wait = Long.parseLong(bootParameter.substring(0, idx));
    if (init_wait < 10000) {
        long on_time = Long.parseLong(bootParameter.substring(idx + 1));
        sendCommand("M5-" + new DecimalFormat("00").format(on_time / 60000));
        return;
    }
    Intent jIntent = new Intent(this, ConnectDaemonService.class);
    //M1-00 (cool) or M1-01 (warm)
    jIntent.setAction(ALARM_1BOOT);
    jIntent.putExtra(ConnectDaemonService.ALARM_DONE, ALARM_1BOOT);
    jIntent.putExtra(ConnectDaemonService.ALARM_1BOOT, bootParameter.substring(idx + 1));
    oneBootIntent = PendingIntent.getService(this, ++boot1AlarmRequestId % 10 + 150, jIntent,
            PendingIntent.FLAG_ONE_SHOT);
    alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + init_wait, oneBootIntent);
    Log.i("ALARM_SET", "to start one boot in " + init_wait / 60000);
    //startScheduledJobs();
}

From source file:org.wso2.emm.agent.services.operation.OperationManagerWorkProfile.java

@Override
public void restrictAccessToApplications(Operation operation) throws AndroidAgentException {
    AppRestriction appRestriction = CommonUtils.getAppRestrictionTypeAndList(operation, getResultBuilder(),
            getContextResources());//  w  w w  .ja va 2  s.com

    if (Constants.AppRestriction.BLACK_LIST.equals(appRestriction.getRestrictionType())) {
        Intent restrictionIntent = new Intent(getContext(), AppLockService.class);
        restrictionIntent.setAction(Constants.APP_LOCK_SERVICE);

        restrictionIntent.putStringArrayListExtra(Constants.AppRestriction.APP_LIST,
                (ArrayList) appRestriction.getRestrictedList());

        PendingIntent pendingIntent = PendingIntent.getService(getContext(), 0, restrictionIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        AlarmManager alarmManager = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.add(Calendar.SECOND, 1); // First time
        long frequency = 1 * 1000; // In ms
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), frequency,
                pendingIntent);

        getContext().startService(restrictionIntent);

    }
    operation.setStatus(getContextResources().getString(R.string.operation_value_completed));
    getResultBuilder().build(operation);
}

From source file:com.money.manager.ex.sync.SyncManager.java

/**
 * Schedule delayed upload via timer.//from w  ww.j  a  v a 2s.  c om
 */
private void scheduleDelayedUpload() {
    PendingIntent pendingIntent = getPendingIntentForDelayedUpload();
    AlarmManager alarm = getAlarmManager();

    Timber.d("Setting delayed upload alarm.");

    // start the sync service after 30 seconds.
    alarm.set(AlarmManager.RTC_WAKEUP, new MmxDate().getMillis() + 30 * 1000, pendingIntent);
}

From source file:com.etime.ETimeActivity.java

/**
 * Set the alarm that will perform autoclock out at the specified time.
 * @param alarmTime time in milliseconds since epoch when the alarm
 *                  should run./*from w w w. j av a 2  s.c  o  m*/
 */
public void setOneTimeAlarm(long alarmTime) {
    Intent intent = new Intent(this, TimeAlarm.class);
    intent.putExtra("username", loginName);
    intent.putExtra("password", password);
    pendingIntentAutoClockAlarm = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
    am.set(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntentAutoClockAlarm);
}