Example usage for android.app AlarmManager set

List of usage examples for android.app AlarmManager set

Introduction

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

Prototype

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

Source Link

Document

Schedule an alarm.

Usage

From source file:com.metinkale.prayerapp.vakit.AlarmReceiver.java

public static void silenter(Context c, long dur) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);
    boolean silent = "silent".equals(prefs.getString("silenterType", "silent"));
    AudioManager aum = (AudioManager) c.getSystemService(Context.AUDIO_SERVICE);
    int ringermode = aum.getRingerMode();
    if ((ringermode != AudioManager.RINGER_MODE_SILENT)
            && ((ringermode != AudioManager.RINGER_MODE_VIBRATE) || silent)) {
        AlarmManager am = (AlarmManager) c.getSystemService(Context.ALARM_SERVICE);

        Intent i;/*w w  w  . j  a v a  2  s  .  co  m*/
        if (ringermode == AudioManager.RINGER_MODE_VIBRATE) {
            i = new Intent(c, setVibrate.class);
        } else {
            i = new Intent(c, setNormal.class);
        }

        PendingIntent service = PendingIntent.getBroadcast(c, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);

        am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (1000 * 60 * dur), service);

        if (PermissionUtils.get(c).pNotPolicy)
            aum.setRingerMode(silent ? AudioManager.RINGER_MODE_SILENT : AudioManager.RINGER_MODE_VIBRATE);

    }
}

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./*from  www  . j a  v  a2 s  .  c  om*/
 * @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.alchemiasoft.book.receiver.SuggestionReceiver.java

/**
 * Schedule a suggestion alarm./*  w ww. j av  a 2s. co m*/
 *
 * @param context reference.
 * @return true if the alarm has been successfully scheduled, false otherwise.
 */
public static boolean scheduleSuggestion(Context context) {
    final AlarmManager alarmManager = AlarmUtil.getAlarmManager(context);
    if (sPendingIntent != null) {
        alarmManager.cancel(sPendingIntent);
    }
    final UserData userData = UserData.load(context);
    final UserData.SuggestionInterval interval = userData.suggestionInterval();
    if (interval == UserData.SuggestionInterval.NEVER) {
        return false;
    }
    final Intent intent = new Intent(SUGGESTION_ACTION);
    sPendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
    final long refreshInMills = interval.seconds() * DateUtils.SECOND_IN_MILLIS;
    Log.d(TAG_LOG, "AlarmReceiver: scheduling suggestion in " + interval.seconds() + " sec(s).");
    alarmManager.set(AlarmManager.RTC, System.currentTimeMillis() + refreshInMills, sPendingIntent);
    return true;
}

From source file:im.vector.activity.CommonActivityUtils.java

/**
 * Restart the application after 100ms//from   ww  w  .j  av  a  2 s .c  o m
 * @param activity activity
 */
public static void restartApp(Context activity) {
    PendingIntent mPendingIntent = PendingIntent.getActivity(activity, 314159,
            new Intent(activity, LoginActivity.class), PendingIntent.FLAG_CANCEL_CURRENT);

    // so restart the application after 100ms
    AlarmManager mgr = (AlarmManager) activity.getSystemService(activity.ALARM_SERVICE);
    mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 50, mPendingIntent);
    System.exit(0);
}

From source file:org.smssecure.smssecure.notifications.MessageNotifier.java

private static void scheduleReminder(Context context, int count) {
    if (count >= SilencePreferences.getRepeatAlertsCount(context)) {
        return;// www . ja  v  a  2s . c  o 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.brayanarias.alarmproject.receiver.AlarmReceiver.java

public static void dismissAlarm(int alarmId, int minutes, Context context) {
    try {/* ww w. j a  v  a2  s.  co  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:org.ohmage.reminders.notif.Notifier.java

private static void setAlarm(Context context, String action, int mins, Bundle extras) {

    Log.v(TAG, "Notifier: Setting alarm(" + mins + ", " + action + ")");

    AlarmManager alarmMan = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    Intent i = new Intent(context, NotifReceiver.class).setAction(action);
    if (extras != null) {
        i.putExtras(extras);//from w  ww. j a  va 2  s .  c  o  m
    }

    PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);

    long elapsed = mins * 60 * 1000;

    alarmMan.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + elapsed, pi);
}

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;/*from   ww w. j a va2 s  .  c  om*/
    }

    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:Main.java

public static void setupNotificationMessage(AlarmManager am, Calendar calendar, int interval,
        PendingIntent sender) {/*from ww w . j  a va  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:nerd.tuxmobil.fahrplan.congress.FahrplanMisc.java

public static void addAlarm(Context context, Lecture lecture, int alarmTimesIndex) {
    int[] alarm_times = { 0, 5, 10, 15, 30, 45, 60 };
    long when;//from  w ww  . jav a 2s  .  c om
    Time time;
    long startTime;
    long startTimeInSeconds = lecture.dateUTC;

    if (startTimeInSeconds > 0) {
        when = startTimeInSeconds;
        startTime = startTimeInSeconds;
        time = new Time();
    } else {
        time = lecture.getTime();
        startTime = time.normalize(true);
        when = time.normalize(true);
    }
    long alarmTimeDiffInSeconds = alarm_times[alarmTimesIndex] * 60 * 1000;
    when -= alarmTimeDiffInSeconds;

    // DEBUG
    // when = System.currentTimeMillis() + (30 * 1000);

    time.set(when);
    MyApp.LogDebug("addAlarm", "Alarm time: " + time.format("%Y-%m-%dT%H:%M:%S%z") + ", in seconds: " + when);

    Intent intent = new Intent(context, AlarmReceiver.class);
    intent.putExtra(BundleKeys.ALARM_LECTURE_ID, lecture.lecture_id);
    intent.putExtra(BundleKeys.ALARM_DAY, lecture.day);
    intent.putExtra(BundleKeys.ALARM_TITLE, lecture.title);
    intent.putExtra(BundleKeys.ALARM_START_TIME, startTime);
    intent.setAction(AlarmReceiver.ALARM_LECTURE);

    intent.setData(Uri.parse("alarm://" + lecture.lecture_id));

    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    PendingIntent pendingintent = PendingIntent.getBroadcast(context, Integer.parseInt(lecture.lecture_id),
            intent, 0);

    // Cancel any existing alarms for this lecture
    alarmManager.cancel(pendingintent);

    // Set new alarm
    alarmManager.set(AlarmManager.RTC_WAKEUP, when, pendingintent);

    int alarmTimeInMin = alarm_times[alarmTimesIndex];

    // write to DB

    AlarmsDBOpenHelper alarmDB = new AlarmsDBOpenHelper(context);

    SQLiteDatabase db = alarmDB.getWritableDatabase();

    // delete any previous alarms of this lecture
    try {
        db.beginTransaction();
        db.delete(AlarmsTable.NAME, AlarmsTable.Columns.EVENT_ID + "=?", new String[] { lecture.lecture_id });

        ContentValues values = new ContentValues();

        values.put(AlarmsTable.Columns.EVENT_ID, Integer.parseInt(lecture.lecture_id));
        values.put(AlarmsTable.Columns.EVENT_TITLE, lecture.title);
        values.put(AlarmsTable.Columns.ALARM_TIME_IN_MIN, alarmTimeInMin);
        values.put(AlarmsTable.Columns.TIME, when);
        DateFormat df = SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.SHORT);
        values.put(AlarmsTable.Columns.TIME_TEXT, df.format(new Date(when)));
        values.put(AlarmsTable.Columns.DISPLAY_TIME, startTime);
        values.put(AlarmsTable.Columns.DAY, lecture.day);

        db.insert(AlarmsTable.NAME, null, values);
        db.setTransactionSuccessful();
    } catch (SQLException e) {
    } finally {
        db.endTransaction();
        db.close();
    }

    lecture.has_alarm = true;
}