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.nextgis.firereporter.GetFiresService.java

protected void ScheduleNextUpdate(Context context, int nCommand, long nMinTimeBetweenSend,
        boolean bEnergyEconomy) {
    if (context == null)
        return;//from  www  . ja v  a 2  s . c o  m

    Intent intent = new Intent(MainActivity.INTENT_NAME);
    intent.putExtra(RECEIVER, mUserNasaReceiver);
    intent.putExtra(RECEIVER_SCANEX, mScanexReceiver);
    intent.putExtra(COMMAND, nCommand);
    intent.putExtra(SOURCE, mnFilter);

    PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    // The update frequency should often be user configurable.  This is not.

    long currentTimeMillis = System.currentTimeMillis();
    long nextUpdateTimeMillis = currentTimeMillis + nMinTimeBetweenSend;
    Time nextUpdateTime = new Time();
    nextUpdateTime.set(nextUpdateTimeMillis);

    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    if (bEnergyEconomy)
        alarmManager.set(AlarmManager.RTC, nextUpdateTimeMillis, pendingIntent);
    else
        alarmManager.set(AlarmManager.RTC_WAKEUP, nextUpdateTimeMillis, pendingIntent);
}

From source file:com.razza.apps.iosched.service.SessionAlarmService.java

private void scheduleAlarm(final long sessionStart, final long sessionEnd, final long alarmOffset) {

    NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    nm.cancel(NOTIFICATION_ID);/* www. j  a v  a2 s.  c om*/
    final long currentTime = UIUtils.getCurrentTime(this);
    // If the session is already started, do not schedule system notification.
    if (currentTime > sessionStart) {
        LogUtils.LOGD(TAG, "Not scheduling alarm because target time is in the past: " + sessionStart);
        return;
    }

    // By default, sets alarm to go off at 10 minutes before session start time.  If alarm
    // offset is provided, alarm is set to go off by that much time from now.
    long alarmTime;
    if (alarmOffset == UNDEFINED_ALARM_OFFSET) {
        alarmTime = sessionStart - MILLI_TEN_MINUTES;
    } else {
        alarmTime = currentTime + alarmOffset;
    }

    LogUtils.LOGD(TAG, "Scheduling alarm for " + alarmTime + " = " + (new Date(alarmTime)).toString());

    final Intent notifIntent = new Intent(ACTION_NOTIFY_SESSION, null, this, SessionAlarmService.class);
    // Setting data to ensure intent's uniqueness for different session start times.
    notifIntent.setData(
            new Uri.Builder().authority("com.razza.apps.iosched").path(String.valueOf(sessionStart)).build());
    notifIntent.putExtra(SessionAlarmService.EXTRA_SESSION_START, sessionStart);
    LogUtils.LOGD(TAG, "-> Intent extra: session start " + sessionStart);
    notifIntent.putExtra(SessionAlarmService.EXTRA_SESSION_END, sessionEnd);
    LogUtils.LOGD(TAG, "-> Intent extra: session end " + sessionEnd);
    notifIntent.putExtra(SessionAlarmService.EXTRA_SESSION_ALARM_OFFSET, alarmOffset);
    LogUtils.LOGD(TAG, "-> Intent extra: session alarm offset " + alarmOffset);
    PendingIntent pi = PendingIntent.getService(this, 0, notifIntent, PendingIntent.FLAG_CANCEL_CURRENT);
    final AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    // Schedule an alarm to be fired to notify user of added sessions are about to begin.
    LogUtils.LOGD(TAG, "-> Scheduling RTC_WAKEUP alarm at " + alarmTime);
    am.set(AlarmManager.RTC_WAKEUP, alarmTime, pi);
}

From source file:com.android.deskclock.timer.TimerReceiver.java

private void updateNextTimesup(Context context) {
    TimerObj t = getNextRunningTimer(mTimers, false, Utils.getTimeNow());
    long nextTimesup = (t == null) ? -1 : t.getTimesupTime();
    int timerId = (t == null) ? -1 : t.mTimerId;

    Intent intent = new Intent();
    intent.setAction(Timers.TIMES_UP);/*from  www .  java2s  .  c om*/
    intent.setClass(context, TimerReceiver.class);
    // Time-critical, should be foreground
    intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
    if (!mTimers.isEmpty()) {
        intent.putExtra(Timers.TIMER_INTENT_EXTRA, timerId);
    }
    AlarmManager mngr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    PendingIntent p = PendingIntent.getBroadcast(context, 0, intent,
            PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);
    if (t != null) {
        if (Utils.isKitKatOrLater()) {
            mngr.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, nextTimesup, p);
        } else {
            mngr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, nextTimesup, p);
        }
        if (Timers.LOGGING) {
            Log.d(TAG, "Setting times up to " + nextTimesup);
        }
    } else {
        // if no timer is found Pending Intents should be canceled
        // to keep the internal state consistent with the UI
        mngr.cancel(p);
        p.cancel();
        if (Timers.LOGGING) {
            Log.v(TAG, "no next times up");
        }
    }
}

From source file:com.mikecorrigan.bohrium.pubsub.RegistrationClient.java

private void c2dmHandleRegistrationResponse(final Context context, Intent intent) {
    Log.d(TAG, "c2dmHandleRegistrationResponse: context=" + context + ", intent=" + intent + ", extras="
            + Utils.bundleToString(intent.getExtras()));

    final String registrationId = intent.getStringExtra(EXTRA_REGISTRATION_ID);
    String error = intent.getStringExtra(EXTRA_ERROR);
    String unregistered = intent.getStringExtra(EXTRA_UNREGISTERED);

    Log.d(TAG, "handleRegistration: registrationId = " + registrationId + ", error = " + error
            + ", unregistered = " + unregistered);

    mConfiguration.putLong(LAST_CHANGE, System.currentTimeMillis());

    if (unregistered != null) {
        // Unregistered
        mConfiguration.putString(REG_ID, "");
        setStateAndNotify(REGISTRATION_STATE_UNREGISTERING, REGISTRATION_SUBSTATE_NONE);

        mHandler.sendEmptyMessage(EVENT_UNREGISTER_COMPLETE);
    } else if (error != null) {
        // Registration failed.
        Log.e(TAG, "Registration error " + error);

        mConfiguration.putString(REG_ID, "");
        setStateAndNotify(REGISTRATION_STATE_ERROR, error);

        if ("SERVICE_NOT_AVAILABLE".equals(error)) {
            long backoffTime = mConfiguration.getLong(C2DM_BACKOFF, DEFAULT_BACKOFF);

            // For this error, try again later.
            Log.d(TAG, "Scheduling registration retry, backoff = " + backoffTime);
            Intent retryIntent = new Intent(C2DM_INTENT_RETRY);
            PendingIntent retryPIntent = PendingIntent.getBroadcast(context, 0 /* requestCode */, retryIntent,
                    0 /* flags */);

            AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            am.set(AlarmManager.ELAPSED_REALTIME, backoffTime, retryPIntent);

            // Next retry should wait longer.
            backoffTime *= BACKOFF_MULTIPLIER;
            if (backoffTime > MAX_BACKOFF) {
                backoffTime = MAX_BACKOFF;

                mConfiguration.putLong(C2DM_BACKOFF, backoffTime);
            }//from www  . j a v  a2 s.  c  om

            // Save the backoff time.
            writePreferences();
        }
    } else {
        mConfiguration.putString(REG_ID, registrationId);
        setStateAndNotify(REGISTRATION_STATE_REGISTERING, REGISTRATION_SUBSTATE_HAVE_REG_ID);

        mHandler.sendEmptyMessage(EVENT_REGISTER_COMPLETE);
    }
}

From source file:co.taqat.call.assistant.AssistantActivity.java

public void restartApplication() {
    mPrefs.firstLaunchSuccessful();//from  w ww.java 2 s .co  m

    Intent mStartActivity = new Intent(this, LinphoneLauncherActivity.class);
    PendingIntent mPendingIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(),
            mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager mgr = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 500, mPendingIntent);

    stopService(new Intent(Intent.ACTION_MAIN).setClass(this, LinphoneService.class));
    android.os.Process.killProcess(android.os.Process.myPid());
}

From source file:net.naonedbus.appwidget.HoraireWidgetProvider.java

/**
 * Programmer le rafraichissement des widgets.
 * /*from   w  ww .j a  va 2  s .c o  m*/
 * @param context
 * @param timestamp
 */
private synchronized void scheduleUpdate(final Context context, final long timestamp) {
    final long now = new DateTime().getMillis();
    final long triggerTimestamp = new DateTime(timestamp).plusMinutes(1).getMillis();

    if (sNextTimestamp < now || triggerTimestamp < sNextTimestamp) {
        sNextTimestamp = triggerTimestamp;

        final AlarmManager m = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        if (sPendingIntent != null) {
            m.cancel(sPendingIntent);

            if (DBG)
                Log.i(LOG_TAG,
                        Integer.toHexString(hashCode()) + " - " + "\tAnnulation de la prcdente alarme.");
        }

        final Intent intent = new Intent(ACTION_APPWIDGET_UPDATE);
        sPendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
        m.set(AlarmManager.RTC, sNextTimestamp, sPendingIntent);

        if (DBG)
            Log.i(LOG_TAG, Integer.toHexString(hashCode()) + " - " + "Programmation de l'alarme  : "
                    + new DateTime(sNextTimestamp).toString());
    }

}

From source file:com.tortel.deploytrack.service.NotificationService.java

@SuppressLint("NewApi")
private void showNotification() {
    // If there isnt an ID saved, shut down the service
    if (deploymentId == -1) {
        stopSelf();/*w  w w . j a  v a2s  .co m*/
        return;
    }
    if (DEBUG) {
        Toast.makeText(this, "NotificationService loading notification", Toast.LENGTH_SHORT).show();
    }

    // Load the Deployment object
    Deployment deployment = DatabaseManager.getInstance(this).getDeployment(deploymentId);
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    RemoteViews view = new RemoteViews(getPackageName(), R.layout.notification);
    view.setImageViewBitmap(R.id.notification_pie, WidgetProvider.getChartBitmap(deployment, SIZE));
    view.setTextViewText(R.id.notification_title, deployment.getName());

    view.setTextViewText(R.id.notification_main, getResources().getString(R.string.small_notification,
            deployment.getPercentage(), deployment.getCompleted(), deployment.getLength()));

    if (prefs.getBoolean(Prefs.KEY_HIDE_DATE, false)) {
        view.setViewVisibility(R.id.notification_daterange, View.GONE);
    } else {
        view.setTextViewText(R.id.notification_daterange, getResources().getString(R.string.date_range,
                deployment.getFormattedStart(), deployment.getFormattedEnd()));
    }

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setContentTitle(deployment.getName());
    builder.setContentText(getResources().getString(R.string.small_notification, deployment.getPercentage(),
            deployment.getCompleted(), deployment.getLength()));
    builder.setOngoing(true);

    // Hide the time, its persistent
    builder.setWhen(0);

    builder.setSmallIcon(R.drawable.ic_notification);
    builder.setPriority(Integer.MAX_VALUE);

    Notification notification = builder.build();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        notification.bigContentView = view;
    }

    notificationManager.notify(NOTIFICATION_ID, notification);

    //Schedule an update at midnight
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    DateTime now = new DateTime();
    DateTime tomorrow = new DateTime(now.plusDays(1)).withTimeAtStartOfDay();

    PendingIntent pending = PendingIntent.getBroadcast(getBaseContext(), 0, new Intent(UPDATE_INTENT),
            PendingIntent.FLAG_UPDATE_CURRENT);

    //Adding 100msec to make sure its triggered after midnight
    Log.d("Scheduling notification update for " + tomorrow.getMillis() + 100);

    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2) {
        alarmManager.setExact(AlarmManager.RTC, tomorrow.getMillis() + 100, pending);
    } else {
        alarmManager.set(AlarmManager.RTC, tomorrow.getMillis() + 100, pending);
    }
}

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  w w  w .  ja v a2s  .  c  o m
    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.pacoapp.paco.triggering.NotificationCreator.java

@SuppressLint("NewApi")
private void createAlarmForSnooze(Context context, NotificationHolder notificationHolder) {
    DateTime alarmTime = new DateTime(notificationHolder.getAlarmTime());
    Experiment experiment = experimentProviderUtil
            .getExperimentByServerId(notificationHolder.getExperimentId());
    Integer snoozeTime = notificationHolder.getSnoozeTime();
    if (snoozeTime == null) {
        snoozeTime = DEFAULT_SNOOZE_10_MINUTES;
    }/*from w  w  w .j  a v a 2s  .  c  om*/
    int snoozeMinutes = snoozeTime / MILLIS_IN_MINUTE;
    DateTime timeoutMinutes = new DateTime(alarmTime).plusMinutes(snoozeMinutes);
    long snoozeDurationInMillis = timeoutMinutes.getMillis();

    Log.info("Creating snooze alarm to resound notification for holder: " + notificationHolder.getId()
            + ". experiment = " + notificationHolder.getExperimentId() + ". alarmtime = "
            + new DateTime(alarmTime).toString() + " waking up from snooze in " + timeoutMinutes + " minutes");

    Intent ultimateIntent = new Intent(context, AlarmReceiver.class);
    Uri uri = Uri.withAppendedPath(NotificationHolderColumns.CONTENT_URI,
            notificationHolder.getId().toString());
    ultimateIntent.setData(uri);
    ultimateIntent.putExtra(NOTIFICATION_ID, notificationHolder.getId().longValue());
    ultimateIntent.putExtra(SNOOZE_REPEATER_EXTRA_KEY, true);

    PendingIntent intent = PendingIntent.getBroadcast(context.getApplicationContext(), 3, 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, snoozeDurationInMillis, intent);
    } else {
        alarmManager.set(AlarmManager.RTC_WAKEUP, snoozeDurationInMillis, intent);
    }

}

From source file:org.dmfs.tasks.notification.NotificationUpdaterService.java

@TargetApi(Build.VERSION_CODES.KITKAT)
private void updateNextDayAlarm() {
    Intent intent = new Intent(this, NotificationUpdaterService.class);
    intent.setAction(ACTION_NEXT_DAY);//from   w w w .  j  ava  2  s .c  om
    mDateChangePendingIntent = PendingIntent.getService(this, 0, intent, 0);

    // set alarm to update the next day
    GregorianCalendar tomorrow = new GregorianCalendar();
    tomorrow.add(Calendar.DAY_OF_YEAR, 1);
    tomorrow.set(Calendar.HOUR_OF_DAY, 0);
    tomorrow.set(Calendar.MINUTE, 0);
    tomorrow.set(Calendar.SECOND, 0);
    tomorrow.set(Calendar.MILLISECOND, 0);

    AlarmManager alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
        alarmManager.setWindow(AlarmManager.RTC, tomorrow.getTimeInMillis(), 1000, mDateChangePendingIntent);
    } else {
        alarmManager.set(AlarmManager.RTC, tomorrow.getTimeInMillis(), mDateChangePendingIntent);
    }
}