Example usage for android.app AlarmManager setExact

List of usage examples for android.app AlarmManager setExact

Introduction

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

Prototype

public void setExact(@AlarmType int type, long triggerAtMillis, PendingIntent operation) 

Source Link

Document

Schedule an alarm to be delivered precisely at the stated time.

Usage

From source file:com.commonsware.android.deepbg.PollReceiver.java

static void scheduleExactAlarm(Context ctxt, AlarmManager alarms, long period, boolean isDownload) {
    Intent i = buildBaseIntent(ctxt).putExtra(EXTRA_PERIOD, period).putExtra(EXTRA_IS_DOWNLOAD, isDownload);
    PendingIntent pi = PendingIntent.getBroadcast(ctxt, 0, i, 0);

    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
        Log.e("PollReceiver", "allow while idle");
        alarms.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                SystemClock.elapsedRealtime() + period, pi);
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        alarms.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + period, pi);
    } else {/*  w  ww.  j av  a 2  s. co  m*/
        alarms.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + period, pi);
    }
}

From source file:Main.java

public static void setupNotificationMessage(AlarmManager am, Calendar calendar, int interval,
        PendingIntent sender) {/*from   w  ww .  j  a v a  2 s.com*/
    // official docs:
    // Note: as of API 19, all repeating alarms are inexact. If your application needs precise 
    // delivery times then it must use one-time exact alarms, rescheduling each time as described above. 
    // Legacy applications whosetargetSdkVersion is earlier than API 19 will continue to have all of their alarms, including repeating alarms, treated as exact.
    if (Build.VERSION.SDK_INT >= FAKE_KITKAT_WATCH) {
        //am.setWindow(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 20000, sender);
        am.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
    } else {
        // use this on sdk level 18 and smaller than 18. later sdk won`t guarantee time to be precise.
        //am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), interval, sender);
        am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
    }
}

From source file:com.lloydtorres.stately.push.TrixHelper.java

/**
 * Sets an alarm for Alphys to query NS for new notices. The alarm time is on whatever the user
 * selected in settings, starting from the time the function was called. A "jitter" of up to
 * 5 minutes is added on top to prevent overwhelming the NS servers.
 * @param c App context/*from  w w  w. java 2  s .  co m*/
 */
public static void setAlarmForAlphys(Context c) {
    // First check if alarms should be set to begin with.
    if (!SettingsActivity.getNotificationSetting(c)) {
        return;
    }

    Intent alphysIntent = new Intent(c, AlphysReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(c, 0, alphysIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    long timeToNextAlarm = System.currentTimeMillis()
            + SettingsActivity.getNotificationIntervalSetting(c) * 1000L;
    // add "jitter" from 0 min to 5 min to next alarm to prevent overwhelming NS servers
    Random r = new Random();
    timeToNextAlarm += (long) (r.nextDouble() * FIVE_MIN_IN_MS);

    // Source:
    // https://www.reddit.com/r/Android/comments/44opi3/reddit_sync_temporarily_blocked_for_bad_api_usage/czs3ne4
    AlarmManager am = (AlarmManager) c.getSystemService(Context.ALARM_SERVICE);
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, timeToNextAlarm, pendingIntent);
    } else if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        am.setExact(AlarmManager.RTC_WAKEUP, timeToNextAlarm, pendingIntent);
    } else {
        am.set(AlarmManager.RTC_WAKEUP, timeToNextAlarm, pendingIntent);
    }
}

From source file:com.ksk.droidbatterybooster.provider.TimeSchedule.java

/**
 * Sets action in AlarmManger.  This is what will
 * actually launch the action when the schedule triggers.
 *
 * @param schedule TimeSchedule.//ww w . j  ava 2s . c o  m
 * @param atTimeInMillis milliseconds since epoch
 */
@SuppressLint("NewApi")
private static void enableAction(Context context, final TimeSchedule schedule, final long atTimeInMillis) {

    if (Log.LOGV) {
        Log.v("** setSchedule id " + schedule.id + " atTime " + atTimeInMillis);
    }

    Intent intent = new Intent(EXECUTE_SCHEDULE_ACTION);

    // XXX: This is a slight hack to avoid an exception in the remote
    // AlarmManagerService process. The AlarmManager adds extra data to
    // this Intent which causes it to inflate. Since the remote process
    // does not know about the TimeSchedule class, it throws a
    // ClassNotFoundException.
    //
    // To avoid this, we marshall the data ourselves and then parcel a plain
    // byte[] array. The ScheduleReceiver class knows to build the TimeSchedule
    // object from the byte[] array.
    Parcel out = Parcel.obtain();
    schedule.writeToParcel(out, 0);
    out.setDataPosition(0);
    intent.putExtra(INTENT_RAW_DATA, out.marshall());

    PendingIntent sender = PendingIntent.getBroadcast(context, schedule.hashCode(), intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    if (Utils.isKitKatOrLater()) {
        am.setExact(AlarmManager.RTC_WAKEUP, atTimeInMillis, sender);
    } else {
        am.set(AlarmManager.RTC_WAKEUP, atTimeInMillis, sender);
    }

    Calendar c = Calendar.getInstance();
    c.setTimeInMillis(atTimeInMillis);
    String timeString = formatDayAndTime(context, c);
    saveNextAlarm(context, timeString);
}

From source file:com.brayanarias.alarmproject.receiver.AlarmReceiver.java

public static void dismissAlarm(int alarmId, int minutes, Context context) {
    try {//w  w  w.  j  av a 2s .  c o  m
        DataBaseManager dataBaseManager = DataBaseManager.getInstance(context);
        Alarm alarm = AlarmDataBase.getAlarmById(dataBaseManager, alarmId);
        PendingIntent pendingIntent = createPendingIntent(context, alarm);
        AlarmManager alarmManager = getAlarmManager(context);
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, minutes);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            AlarmManager.AlarmClockInfo clockInfo = new AlarmManager.AlarmClockInfo(calendar.getTimeInMillis(),
                    pendingIntent);
            alarmManager.setAlarmClock(clockInfo, pendingIntent);
        } else if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
        } else {
            alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
        }
    } catch (Exception e) {
        Log.e(tag, e.getMessage(), e);
    }
}

From source file:com.brayanarias.alarmproject.receiver.AlarmReceiver.java

private static void setAlarmCumple(Context context) {
    PendingIntent pendingIntent = null;//  ww w .j  a  va2 s.c  om
    Intent intent = new Intent(context, AlarmService.class);
    intent.putExtra(Constant.alarmIdKey, 2809);
    intent.putExtra(Constant.alarmNameKey, "Feliz cumple mamita");
    pendingIntent = PendingIntent.getService(context, 2809, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager = getAlarmManager(context);
    Calendar actual = Calendar.getInstance();
    actual.set(Calendar.MONTH, 8);
    actual.set(Calendar.DAY_OF_MONTH, 28);
    actual.set(Calendar.SECOND, 0);
    actual.set(Calendar.MILLISECOND, 0);
    actual.set(Calendar.HOUR, 5);
    actual.set(Calendar.AM_PM, Calendar.AM);
    actual.set(Calendar.MINUTE, 0);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        AlarmManager.AlarmClockInfo clockInfo = new AlarmManager.AlarmClockInfo(actual.getTimeInMillis(),
                pendingIntent);
        alarmManager.setAlarmClock(clockInfo, pendingIntent);
    } else if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, actual.getTimeInMillis(), pendingIntent);
    } else {
        alarmManager.set(AlarmManager.RTC_WAKEUP, actual.getTimeInMillis(), pendingIntent);
    }
}

From source file:com.androidinspain.deskclock.data.TimerModel.java

static void schedulePendingIntent(AlarmManager am, long triggerTime, PendingIntent pi) {
    if (Utils.isMOrLater()) {
        // Ensure the timer fires even if the device is dozing.
        am.setExactAndAllowWhileIdle(ELAPSED_REALTIME_WAKEUP, triggerTime, pi);
    } else {/*w  w w . ja  v  a 2 s  .c o m*/
        am.setExact(ELAPSED_REALTIME_WAKEUP, triggerTime, pi);
    }
}

From source file:au.com.smarttrace.beacons.BluetoothService.java

private void connect() {
    btScanner = btAdapter.getBluetoothLeScanner();
    if (btScanner != null && btAdapter.isEnabled()) {

        Log.d(TAG, "START SCANNING!");
        btScanner.startScan(btFilters, btSettings, scanCallback);
        scanning = true;// w  w w  .j  a va  2  s .  com
        sendChange(true);

        //XXX: workaround to avoid bluetooth scan halt
        AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
        Intent intent = new Intent(BluetoothService.ACTION_RESCAN, null, this, BluetoothService.class);
        alarm.setExact(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 15000l,
                PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));

        //         future = executor.schedule(this, DELAY_REPEAT_SCAN, TimeUnit.SECONDS);
    }
}

From source file:com.android.cts.verifier.sensors.SignificantMotionTestActivity.java

@SuppressWarnings("unused")
public String testAPWakeUpOnSMDTrigger() throws Throwable {
    SensorTestLogger logger = getTestLogger();
    logger.logInstructions(R.string.snsr_significant_motion_ap_suspend);
    waitForUserToBegin();//from  www .java2  s. co  m
    mVerifier = new TriggerVerifier();
    mSensorManager.requestTriggerSensor(mVerifier, mSensorSignificantMotion);
    long testStartTimeNs = SystemClock.elapsedRealtimeNanos();
    Handler handler = new Handler(Looper.getMainLooper());
    SuspendStateMonitor suspendStateMonitor = new SuspendStateMonitor();

    Intent intent = new Intent(this, AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);

    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
    am.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + ALARM_WAKE_TIME_DELAY_MS,
            pendingIntent);
    try {
        // Wait for the first event to trigger. Device is expected to go into suspend here.
        mVerifier.verifyEventTriggered();
        long eventTimeStampNs = mVerifier.getTimeStampForTriggerEvent();
        long endTimeNs = SystemClock.elapsedRealtimeNanos();
        long lastWakeupTimeNs = TimeUnit.MILLISECONDS.toNanos(suspendStateMonitor.getLastWakeUpTime());
        Assert.assertTrue(getString(R.string.snsr_device_did_not_go_into_suspend),
                testStartTimeNs < lastWakeupTimeNs && lastWakeupTimeNs < endTimeNs);
        long timestampDelta = Math.abs(lastWakeupTimeNs - eventTimeStampNs);
        Assert.assertTrue(
                String.format(getString(R.string.snsr_device_did_not_wake_up_at_trigger),
                        TimeUnit.NANOSECONDS.toMillis(lastWakeupTimeNs),
                        TimeUnit.NANOSECONDS.toMillis(eventTimeStampNs)),
                timestampDelta < MAX_ACCEPTABLE_DELAY_EVENT_AP_WAKE_UP_NS);
    } finally {
        am.cancel(pendingIntent);
        suspendStateMonitor.cancel();
        mScreenManipulator.turnScreenOn();
        playSound();
    }
    return null;
}

From source file:felixwiemuth.lincal.NotificationService.java

@Override
protected void onHandleIntent(Intent intent) {
    calendars = Calendars.getInstance(this);
    Calendar now = Calendar.getInstance();
    Calendar nextAlarm = null;//  w  w w  .  j av a2  s. c o m
    for (int i = 0; i < calendars.getCalendarCount(); i++) {
        LinCalConfig config = calendars.getConfigByPos(i);
        if (config.isNotificationsEnabled()) { // only load calendar if notifications are enabled
            LinCal cal = calendars.getCalendarByPos(this, i);
            if (cal != null) { // if the calendar could not be loaded, skip it (this will also skip scheduling of next notifications for this calendar)
                Calendar nextTime = processCalendar(cal, config, now);
                if (nextAlarm == null || (nextTime != null && nextTime.before(nextAlarm))) {
                    nextAlarm = nextTime;
                }
            }
        }
    }
    calendars.save(this);
    // Schedule next processing if there are further entries
    if (nextAlarm != null) {
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        Intent processIntent = new Intent(this, NotificationService.class);
        PendingIntent alarmIntent = PendingIntent.getService(this, 0, processIntent, 0);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            alarmManager.setExact(AlarmManager.RTC_WAKEUP, nextAlarm.getTimeInMillis(), alarmIntent);
        } else {
            alarmManager.set(AlarmManager.RTC_WAKEUP, nextAlarm.getTimeInMillis(), alarmIntent);
        }
    }
    stopSelf();
}