Example usage for android.app AlarmManager cancel

List of usage examples for android.app AlarmManager cancel

Introduction

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

Prototype

public void cancel(OnAlarmListener listener) 

Source Link

Document

Remove any alarm scheduled to be delivered to the given OnAlarmListener .

Usage

From source file:org.ohmage.reminders.types.location.LocTrigService.java

private void setKeepAliveAlarm(Context context) {
    Intent i = new Intent(ACTION_ALRM_SRV_KEEP_ALIVE).setPackage(context.getPackageName());

    //set the alarm if not already existing
    PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, PendingIntent.FLAG_NO_CREATE);

    AlarmManager alarmMan = (AlarmManager) getSystemService(ALARM_SERVICE);
    if (pi != null) {
        alarmMan.cancel(pi);
        pi.cancel();/*from  w w  w .j av a 2  s .c o  m*/
    }

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

    alarmMan.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
            SystemClock.elapsedRealtime() + SERV_KEEP_ALIVE_TIME, SERV_KEEP_ALIVE_TIME, pi);
}

From source file:org.ohmage.triggers.types.location.LocTrigService.java

private void setKeepAliveAlarm() {
    Intent i = new Intent(ACTION_ALRM_SRV_KEEP_ALIVE);

    //set the alarm if not already existing
    PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, PendingIntent.FLAG_NO_CREATE);

    AlarmManager alarmMan = (AlarmManager) getSystemService(ALARM_SERVICE);
    if (pi != null) {
        alarmMan.cancel(pi);
        pi.cancel();//from w w  w. j a v a 2 s .  co m
    }

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

    alarmMan.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
            SystemClock.elapsedRealtime() + SERV_KEEP_ALIVE_TIME, SERV_KEEP_ALIVE_TIME, pi);
}

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 ww  w  .j a  v a2 s . c  o 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:com.androidinspain.deskclock.data.TimerNotificationBuilder.java

public Notification build(Context context, NotificationModel nm, List<Timer> unexpired) {
    final Timer timer = unexpired.get(0);
    final int count = unexpired.size();

    // Compute some values required below.
    final boolean running = timer.isRunning();
    final Resources res = context.getResources();

    final long base = getChronometerBase(timer);
    final String pname = context.getPackageName();

    final List<Action> actions = new ArrayList<>(2);

    final CharSequence stateText;
    if (count == 1) {
        if (running) {
            // Single timer is running.
            if (TextUtils.isEmpty(timer.getLabel())) {
                stateText = res.getString(com.androidinspain.deskclock.R.string.timer_notification_label);
            } else {
                stateText = timer.getLabel();
            }/* ww  w.j a  va 2s. c om*/

            // Left button: Pause
            final Intent pause = new Intent(context, TimerService.class)
                    .setAction(TimerService.ACTION_PAUSE_TIMER)
                    .putExtra(TimerService.EXTRA_TIMER_ID, timer.getId());

            @DrawableRes
            final int icon1 = com.androidinspain.deskclock.R.drawable.ic_pause_24dp;
            final CharSequence title1 = res.getText(com.androidinspain.deskclock.R.string.timer_pause);
            final PendingIntent intent1 = Utils.pendingServiceIntent(context, pause);
            actions.add(new Action.Builder(icon1, title1, intent1).build());

            // Right Button: +1 Minute
            final Intent addMinute = new Intent(context, TimerService.class)
                    .setAction(TimerService.ACTION_ADD_MINUTE_TIMER)
                    .putExtra(TimerService.EXTRA_TIMER_ID, timer.getId());

            @DrawableRes
            final int icon2 = com.androidinspain.deskclock.R.drawable.ic_add_24dp;
            final CharSequence title2 = res.getText(com.androidinspain.deskclock.R.string.timer_plus_1_min);
            final PendingIntent intent2 = Utils.pendingServiceIntent(context, addMinute);
            actions.add(new Action.Builder(icon2, title2, intent2).build());

        } else {
            // Single timer is paused.
            stateText = res.getString(com.androidinspain.deskclock.R.string.timer_paused);

            // Left button: Start
            final Intent start = new Intent(context, TimerService.class)
                    .setAction(TimerService.ACTION_START_TIMER)
                    .putExtra(TimerService.EXTRA_TIMER_ID, timer.getId());

            @DrawableRes
            final int icon1 = com.androidinspain.deskclock.R.drawable.ic_start_24dp;
            final CharSequence title1 = res.getText(com.androidinspain.deskclock.R.string.sw_resume_button);
            final PendingIntent intent1 = Utils.pendingServiceIntent(context, start);
            actions.add(new Action.Builder(icon1, title1, intent1).build());

            // Right Button: Reset
            final Intent reset = new Intent(context, TimerService.class)
                    .setAction(TimerService.ACTION_RESET_TIMER)
                    .putExtra(TimerService.EXTRA_TIMER_ID, timer.getId());

            @DrawableRes
            final int icon2 = com.androidinspain.deskclock.R.drawable.ic_reset_24dp;
            final CharSequence title2 = res.getText(com.androidinspain.deskclock.R.string.sw_reset_button);
            final PendingIntent intent2 = Utils.pendingServiceIntent(context, reset);
            actions.add(new Action.Builder(icon2, title2, intent2).build());
        }
    } else {
        if (running) {
            // At least one timer is running.
            stateText = res.getString(com.androidinspain.deskclock.R.string.timers_in_use, count);
        } else {
            // All timers are paused.
            stateText = res.getString(com.androidinspain.deskclock.R.string.timers_stopped, count);
        }

        final Intent reset = TimerService.createResetUnexpiredTimersIntent(context);

        @DrawableRes
        final int icon1 = com.androidinspain.deskclock.R.drawable.ic_reset_24dp;
        final CharSequence title1 = res.getText(com.androidinspain.deskclock.R.string.timer_reset_all);
        final PendingIntent intent1 = Utils.pendingServiceIntent(context, reset);
        actions.add(new Action.Builder(icon1, title1, intent1).build());
    }

    // Intent to load the app and show the timer when the notification is tapped.
    final Intent showApp = new Intent(context, TimerService.class).setAction(TimerService.ACTION_SHOW_TIMER)
            .putExtra(TimerService.EXTRA_TIMER_ID, timer.getId())
            .putExtra(Events.EXTRA_EVENT_LABEL, com.androidinspain.deskclock.R.string.label_notification);

    final PendingIntent pendingShowApp = PendingIntent.getService(context, REQUEST_CODE_UPCOMING, showApp,
            PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);

    final Builder notification = new NotificationCompat.Builder(context).setOngoing(true).setLocalOnly(true)
            .setShowWhen(false).setAutoCancel(false).setContentIntent(pendingShowApp)
            .setPriority(Notification.PRIORITY_HIGH).setCategory(NotificationCompat.CATEGORY_ALARM)
            .setSmallIcon(com.androidinspain.deskclock.R.drawable.stat_notify_timer)
            .setSortKey(nm.getTimerNotificationSortKey()).setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setStyle(new NotificationCompat.DecoratedCustomViewStyle())
            .setColor(ContextCompat.getColor(context, com.androidinspain.deskclock.R.color.default_background));

    for (Action action : actions) {
        notification.addAction(action);
    }

    if (Utils.isNOrLater()) {
        notification.setCustomContentView(buildChronometer(pname, base, running, stateText))
                .setGroup(nm.getTimerNotificationGroupKey());
    } else {
        final CharSequence contentTextPreN;
        if (count == 1) {
            contentTextPreN = TimerStringFormatter.formatTimeRemaining(context, timer.getRemainingTime(),
                    false);
        } else if (running) {
            final String timeRemaining = TimerStringFormatter.formatTimeRemaining(context,
                    timer.getRemainingTime(), false);
            contentTextPreN = context.getString(com.androidinspain.deskclock.R.string.next_timer_notif,
                    timeRemaining);
        } else {
            contentTextPreN = context.getString(com.androidinspain.deskclock.R.string.all_timers_stopped_notif);
        }

        notification.setContentTitle(stateText).setContentText(contentTextPreN);

        final AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        final Intent updateNotification = TimerService.createUpdateNotificationIntent(context);
        final long remainingTime = timer.getRemainingTime();
        if (timer.isRunning() && remainingTime > MINUTE_IN_MILLIS) {
            // Schedule a callback to update the time-sensitive information of the running timer
            final PendingIntent pi = PendingIntent.getService(context, REQUEST_CODE_UPCOMING,
                    updateNotification, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);

            final long nextMinuteChange = remainingTime % MINUTE_IN_MILLIS;
            final long triggerTime = SystemClock.elapsedRealtime() + nextMinuteChange;
            TimerModel.schedulePendingIntent(am, triggerTime, pi);
        } else {
            // Cancel the update notification callback.
            final PendingIntent pi = PendingIntent.getService(context, 0, updateNotification,
                    PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_NO_CREATE);
            if (pi != null) {
                am.cancel(pi);
                pi.cancel();
            }
        }
    }

    return notification.build();
}

From source file:org.tigase.messenger.phone.pro.service.XMPPService.java

private void stopKeepAlive() {
    Intent i = new Intent();
    i.setClass(this, XMPPService.class);
    i.setAction(KEEPALIVE_ACTION);// ww  w.ja va 2 s . c  om
    PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
    AlarmManager alarmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmMgr.cancel(pi);
}

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

private void scheduleNotificationRepeat() {
    try {/*from   www . j  av  a2 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.t2.compassionMeditation.Graphs1Activity.java

@Override
protected void onDestroy() {
    super.onDestroy();

    if (mInternalSensorMonitoring) {
        // And cancel the alarm.
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        am.cancel(mBigBrotherService);

        Intent intent = new Intent();
        intent.setAction(BigBrotherConstants.ACTION_COMMAND_BROADCAST);
        intent.putExtra("message", BigBrotherConstants.SERVICE_OFF);
        sendBroadcast(intent);/*from  ww  w.jav a  2 s .c  o m*/

        // Tell the user about what we did.
        Toast.makeText(Graphs1Activity.this, R.string.service_unscheduled, Toast.LENGTH_LONG).show();
    }

    mDataOutHandler.close();

    if (mDataUpdateTimer != null) {
        mDataUpdateTimer.cancel();
        mDataUpdateTimer.purge();
    }

    if (mRespRateAverageTimer != null) {
        mRespRateAverageTimer.cancel();
        mRespRateAverageTimer.purge();
    }

    Log.i(TAG, this.getClass().getSimpleName() + ".onDestroy()");

    // Send stop command to every shimmer device
    // You might think that it would be better to iterate through the mBioSensors table
    // instead of the mBioParameters table but it's actually easier this way
    for (GraphBioParameter param : mBioParameters) {
        if (param.isShimmer && param.shimmerNode != null) {
            ShimmerNonSpineSetupSensor setup = new ShimmerNonSpineSetupSensor();
            setup.setSensor(param.shimmerSensorConstant);

            String deviceAddress = SharedPref.getDeviceForParam(this, param.title1);
            if (deviceAddress != null) {

                setup.setBtAddress(Util.AsciiBTAddressToBytes(deviceAddress));
                setup.setCommand(ShimmerNonSpineSetupSensor.SHIMMER_COMMAND_STOPPED);

                Log.d(TAG, String.format("Setting up Shimmer sensor: %s (%s) (%d) SHIMMER_COMMAND_STOPPED",
                        param.shimmerNode.getPhysicalID(), deviceAddress, param.shimmerSensorConstant));
                mManager.setup(param.shimmerNode, setup);

            }
        }
    }
    this.unregisterReceiver(this.mCommandReceiver);
}

From source file:com.gpsmobitrack.gpstracker.MenuItems.SettingsPage.java

/**
 * Start the alarm service //from   w w  w.  j a  v  a  2s .c om
 * @param pos
 */
private void startAlarmService(int pos) {
    editor.putLong(AppConstants.FREQ_UPDATE_PREF, updateDurationValue[pos]);
    editor.commit();
    int updateTimeint = updateDurationValue[pos];
    AlarmManager alarm = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
    Calendar cal = Calendar.getInstance();
    Intent intent2 = new Intent(getActivity(), BackgroundService.class);
    PendingIntent pintent = PendingIntent.getService(getActivity(), 0, intent2, 0);
    if (PendingIntent.getService(getActivity(), 0, intent2, PendingIntent.FLAG_NO_CREATE) != null) {
        alarm.cancel(pintent);
    }
    alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), (updateTimeint * 1000 * 60), pintent);
}

From source file:com.xorcode.andtweet.AndTweetService.java

/**
 * Cancels the repeating Alarm that sends the fetch Intent.
 *///from  w  w  w  . j av  a  2s.  c om
private boolean cancelRepeatingAlarm() {
    final AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    final PendingIntent pIntent = getRepeatingIntent();
    am.cancel(pIntent);
    MyLog.d(TAG, "Cancelled repeating alarm.");
    return true;
}

From source file:org.apps8os.motivator.services.NotificationService.java

@Override
protected void onHandleIntent(Intent intent) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    if (prefs.getBoolean(SettingsActivity.KEY_SEND_NOTIFICATIONS, true)) {
        // Set up the notification with a builder
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        Bundle extras = intent.getExtras();

        // Check the notification type.
        int notificationType = extras.getInt(NOTIFICATION_TYPE);
        if (notificationType == NOTIFICATION_MOOD) {
            // Cancel all previous notifications.
            manager.cancelAll();/*from   www  . j  a  v a2s  . c  om*/

            SprintDataHandler dataHandler = new SprintDataHandler(this);
            Sprint currentSprint = dataHandler.getCurrentSprint();
            AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            // If there is no current sprint, cancel alarms.
            if (currentSprint == null) {
                Sprint latestEndedSprint = dataHandler.getLatestEndedSprint();
                if (latestEndedSprint != null) {
                    if (latestEndedSprint.endedYesterday()) {
                        builder.setContentTitle(getString(R.string.completed_sprint));
                        builder.setSmallIcon(R.drawable.ic_stat_notification_icon_1);
                        builder.setAutoCancel(true);
                        Intent resultIntent = new Intent(this, MainActivity.class);
                        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
                        stackBuilder.addParentStack(MainActivity.class);
                        stackBuilder.addNextIntent(resultIntent);
                        PendingIntent pendingResultIntent = stackBuilder.getPendingIntent(0,
                                PendingIntent.FLAG_CANCEL_CURRENT);
                        builder.setContentIntent(pendingResultIntent);
                        manager.notify(NOTIFICATION_ID_SPRINT_ENDED, builder.build());
                    }
                }
                Intent notificationIntent = new Intent(this, NotificationService.class);
                PendingIntent pendingNotificationIntent = PendingIntent.getService(this, 0, notificationIntent,
                        PendingIntent.FLAG_CANCEL_CURRENT);
                alarmManager.cancel(pendingNotificationIntent);
            } else {
                builder.setContentTitle(getString(R.string.today_screen_mood));
                int currentDateInSprint = currentSprint.getCurrentDayOfTheSprint();

                builder.setSmallIcon(R.drawable.ic_stat_notification_icon_1);
                // Remove the notification when the user clicks it.
                builder.setAutoCancel(true);

                // Where to go when user clicks the notification
                Intent resultIntent = new Intent(this, MoodQuestionActivity.class);
                DayDataHandler moodDataHandler = new DayDataHandler(this);

                // Check if there were events yesterday.
                DayInHistory yesterday = moodDataHandler.getDayInHistory(
                        System.currentTimeMillis() - TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS));
                yesterday.setEvents();
                ArrayList<MotivatorEvent> yesterdayEvents = yesterday.getUncheckedEvents(this);
                if (!yesterdayEvents.isEmpty()) {
                    // Put the events as extras to the intent so that we can pass them to the checking activity.
                    resultIntent.putExtra(MotivatorEvent.YESTERDAYS_EVENTS, yesterdayEvents);
                    resultIntent.putExtra(EventDataHandler.EVENTS_TO_CHECK, true);
                    builder.setContentText(getString(R.string.you_had_an_event_yesterday));
                } else {
                    // No events to check.
                    resultIntent.putExtra(EventDataHandler.EVENTS_TO_CHECK, false);
                    EventDataHandler eventHandler = new EventDataHandler(this);
                    long lastAddedEventTimestamp = eventHandler.getLatestAddedEventTimestamp();
                    if (lastAddedEventTimestamp != 0L && System.currentTimeMillis()
                            - lastAddedEventTimestamp > TimeUnit.MILLISECONDS.convert(7, TimeUnit.DAYS)) {
                        builder.setContentText(getString(R.string.plan_reminder));
                    } else {
                        builder.setContentText(getString(R.string.today_is_the_day) + " " + currentDateInSprint
                                + "/" + currentSprint.getDaysInSprint() + " - "
                                + currentSprint.getSprintTitle());
                    }
                }
                // Preserve the normal navigation of the app by adding the parent stack of the result activity
                TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
                stackBuilder.addParentStack(MoodQuestionActivity.class);
                stackBuilder.addNextIntent(resultIntent);
                PendingIntent pendingResultIntent = stackBuilder.getPendingIntent(0,
                        PendingIntent.FLAG_CANCEL_CURRENT);
                builder.setContentIntent(pendingResultIntent);
                manager.notify(NOTIFICATION_ID_MOOD, builder.build());
            }
        }

        else if (notificationType == NOTIFICATION_EVENT_START) {
            // Set up a notification for the start of an event.
            int eventId = extras.getInt(EventDataHandler.EVENT_ID);
            String eventName = extras.getString(EventDataHandler.EVENT_NAME);
            builder.setContentTitle(getString(R.string.you_have_an_event_starting));
            builder.setContentText(eventName);
            builder.setSmallIcon(R.drawable.ic_stat_notification_icon_1);
            // Remove the notification when the user clicks it.
            builder.setAutoCancel(true);

            Intent resultIntent = new Intent(this, EventDetailsActivity.class);
            resultIntent.putExtra(EventDataHandler.EVENT_ID, eventId);
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
            stackBuilder.addParentStack(EventDetailsActivity.class);
            stackBuilder.addNextIntent(resultIntent);
            PendingIntent pendingResultIntent = stackBuilder.getPendingIntent(0,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            builder.setContentIntent(pendingResultIntent);

            manager.notify(eventId, builder.build());
        }

        else if (notificationType == NOTIFICATION_EVENT_END) {
            // Set up a notification for the start of an event.
            int eventId = extras.getInt(EventDataHandler.EVENT_ID);
            builder.setContentTitle(getString(R.string.event_ending));
            builder.setContentText(getString(R.string.go_home));
            builder.setSmallIcon(R.drawable.ic_stat_notification_icon_1);
            // Remove the notification when the user clicks it.
            builder.setAutoCancel(true);

            Intent resultIntent = new Intent(this, EventDetailsActivity.class);
            resultIntent.putExtra(EventDataHandler.EVENT_ID, eventId);
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
            stackBuilder.addParentStack(EventDetailsActivity.class);
            stackBuilder.addNextIntent(resultIntent);
            PendingIntent pendingResultIntent = stackBuilder.getPendingIntent(0,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            builder.setContentIntent(pendingResultIntent);

            manager.notify(eventId + 10000, builder.build());
        }
    }
}