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.restcomm.app.qoslib.Services.TrackingManager.java

/**
 * Cancels all scheduled tracking events.
 * Does not stop a currently running tracking event.
 */// www. ja v a 2s  .  c  o m
public void cancelScheduledEvents() {
    //if(timer != null) {
    //   timer.cancel();
    //   timer = null;
    //}
    try {
        LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "cancelScheduledEvents", "");
        bTracking = false;

        if (prevTrackingTime > 0) {
            trackingElapsed += (System.currentTimeMillis() - prevTrackingTime + 500) / 1000;
            PreferenceManager.getDefaultSharedPreferences(owner).edit()
                    .putInt(PreferenceKeys.Miscellaneous.TRACKING_ELAPSED, trackingElapsed).commit();
            if (durMinutes > 0 && trackingElapsed >= (durMinutes - 1) * 60) {
                testTrigger = "";
            }
        }
        prevTrackingTime = System.currentTimeMillis();

        if (testTrigger.equals(""))
            trackingElapsed = 1000000;
        //trackingExpires = System.currentTimeMillis() - 10000;
        PreferenceManager.getDefaultSharedPreferences(owner).edit()
                .putInt(PreferenceKeys.Miscellaneous.TRACKING_ELAPSED, trackingElapsed).commit();
        PreferenceManager.getDefaultSharedPreferences(owner).edit()
                .putLong(PreferenceKeys.Miscellaneous.ENGINEER_MODE_EXPIRES_TIME, 0L).commit();

        AlarmManager alarmMgr = (AlarmManager) owner.getSystemService(Service.ALARM_SERVICE);
        Intent intent = new Intent(IntentHandler.ACTION_TRACKING_5MINUTE);
        PendingIntent alarm = PendingIntent.getBroadcast(owner, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        alarmMgr.cancel(alarm);
        handler.removeCallbacks(testRunnable);

    } catch (Exception e) {
        LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "cancelScheduledEvents", "Exception", e);
    }
}

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

public void scheduleStartBlockchainService() {

    final WalletApplication wa = this;

    this.setOnLoadedCallback(new Runnable() {

        @Override//from w w  w.  java  2  s.  co  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:com.lambdasoup.quickfit.alarm.AlarmService.java

/**
 * sets the alarm with the alarm manager for the next occurrence of any scheduled event according
 * to the current db state/*ww  w .j a  va2  s  .  c om*/
 */
@WorkerThread
private void setNextAlarm() {
    try (SQLiteDatabase db = dbHelper.getReadableDatabase();
            Cursor cursor = db.rawQuery(QUERY_SELECT_MIN_NEXT_ALERT, null)) {
        // if cursor is empty, no schedules exist, no alarms to set
        if (cursor.moveToFirst()) {
            long nextAlarmMillis = cursor
                    .getLong(cursor.getColumnIndexOrThrow(ScheduleEntry.COL_NEXT_ALARM_MILLIS));

            AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
            PendingIntent alarmReceiverIntent = PendingIntent.getBroadcast(this, PENDING_INTENT_ALARM_RECEIVER,
                    AlarmReceiver.getIntentOnAlarm(this), PendingIntent.FLAG_UPDATE_CURRENT);
            alarmManager.cancel(alarmReceiverIntent);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, nextAlarmMillis,
                        alarmReceiverIntent);
            } else {
                alarmManager.setWindow(AlarmManager.RTC_WAKEUP, nextAlarmMillis, DateUtils.MINUTE_IN_MILLIS,
                        alarmReceiverIntent);
            }
        }
    }
}

From source file:org.numixproject.hermes.irc.IRCService.java

/**
 * On Destroy//  ww w .j  ava 2  s .  com
 */
@Override
public void onDestroy() {
    unregisterReceiver(disconnectReceiver);

    // Restore AdMob counter
    SharedPreferences sp = getSharedPreferences("preference name", MODE_PRIVATE);
    SharedPreferences.Editor ed = sp.edit();
    ed.putInt("key", 0);
    ed.commit();

    // Make sure our notification is gone.
    if (foreground) {
        stopForegroundCompat(R.string.app_name);
    }

    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
    synchronized (alarmIntentsLock) {
        for (PendingIntent pendingRIntent : alarmIntents.values()) {
            am.cancel(pendingRIntent);
        }
        for (ReconnectReceiver receiver : alarmReceivers.values()) {
            unregisterReceiver(receiver);
        }
        alarmIntents.clear();
        alarmIntents = null;
        alarmReceivers.clear();
        alarmReceivers = null;
    }
}

From source file:com.battlelancer.seriesguide.service.NotificationService.java

@SuppressLint("CommitPrefEdits")
@TargetApi(android.os.Build.VERSION_CODES.KITKAT)
@Override/* www.  j ava2 s  . c  o m*/
protected void onHandleIntent(Intent intent) {
    Timber.d("Waking up...");
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    /*
     * Handle a possible delete intent.
     */
    if (handleDeleteIntent(this, intent)) {
        return;
    }

    /*
     * Unschedule notification service wake-ups for disabled notifications
     * and non-supporters.
     */
    if (!NotificationSettings.isNotificationsEnabled(this) || !Utils.hasAccessToX(this)) {
        Timber.d("Notification service disabled, removing wakup-up alarm");
        // cancel any pending alarm
        AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent i = new Intent(this, OnAlarmReceiver.class);
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
        am.cancel(pi);

        resetLastEpisodeAirtime(prefs);

        return;
    }

    long wakeUpTime = 0;

    /*
     * Get pool of episodes which air from 12 hours ago until eternity which
     * match the users settings.
     */
    StringBuilder selection = new StringBuilder(SELECTION);
    boolean isFavsOnly = NotificationSettings.isNotifyAboutFavoritesOnly(this);
    Timber.d("Do notify about " + (isFavsOnly ? "favorites ONLY" : "ALL"));
    if (isFavsOnly) {
        selection.append(" AND ").append(Shows.SELECTION_FAVORITES);
    }
    boolean isNoSpecials = DisplaySettings.isHidingSpecials(this);
    Timber.d("Do " + (isNoSpecials ? "NOT " : "") + "notify about specials");
    if (isNoSpecials) {
        selection.append(" AND ").append(Episodes.SELECTION_NO_SPECIALS);
    }
    // always exclude hidden shows
    selection.append(" AND ").append(Shows.SELECTION_NO_HIDDEN);

    final long customCurrentTime = TimeTools.getCurrentTime(this);
    final Cursor upcomingEpisodes = getContentResolver().query(Episodes.CONTENT_URI_WITHSHOW, PROJECTION,
            selection.toString(),
            new String[] { String.valueOf(customCurrentTime - 12 * DateUtils.HOUR_IN_MILLIS) }, SORTING);

    if (upcomingEpisodes != null) {
        int notificationThreshold = NotificationSettings.getLatestToIncludeTreshold(this);
        if (DEBUG) {
            Timber.d("DEBUG MODE: notification threshold is 1 week");
            // a week, for debugging (use only one show to get single
            // episode notifications)
            notificationThreshold = 10080;
            // notify again for same episodes
            resetLastEpisodeAirtime(prefs);
        }

        final long nextEpisodeReleaseTime = NotificationSettings.getNextToNotifyAbout(this);
        // wake user-defined amount of time earlier than next episode release time
        final long plannedWakeUpTime = TimeTools.getEpisodeReleaseTime(this, nextEpisodeReleaseTime).getTime()
                - DateUtils.MINUTE_IN_MILLIS * notificationThreshold;

        /*
         * Set to -1 as on first run nextTimePlanned will be 0. This assures
         * we still see notifications of upcoming episodes then.
         */
        int newEpisodesAvailable = -1;

        // Check if we did wake up earlier than planned
        if (System.currentTimeMillis() < plannedWakeUpTime) {
            Timber.d("Woke up earlier than planned, checking for new episodes");
            newEpisodesAvailable = 0;
            long latestTimeNotified = NotificationSettings.getLastNotified(this);

            // Check if there are any earlier episodes to notify about
            while (upcomingEpisodes.moveToNext()) {
                final long releaseTime = upcomingEpisodes.getLong(NotificationQuery.EPISODE_FIRST_RELEASE_MS);
                if (releaseTime < nextEpisodeReleaseTime) {
                    if (releaseTime > latestTimeNotified) {
                        /**
                         * This will not get new episodes which would have
                         * aired the same time as the last one we notified
                         * about. Sad, but the best we can do right now.
                         */
                        newEpisodesAvailable = 1;
                        break;
                    }
                } else {
                    break;
                }
            }
        }

        if (newEpisodesAvailable == 0) {
            // Go to sleep, wake up as planned
            Timber.d("No new episodes, going to sleep.");
            wakeUpTime = plannedWakeUpTime;
        } else {
            // Get episodes which are within the notification threshold
            // (user set) and not yet cleared
            final List<Integer> notifyPositions = new ArrayList<>();
            final long latestTimeCleared = NotificationSettings.getLastCleared(this);
            final long latestTimeToInclude = customCurrentTime
                    + DateUtils.MINUTE_IN_MILLIS * notificationThreshold;

            int position = -1;
            upcomingEpisodes.moveToPosition(position);
            while (upcomingEpisodes.moveToNext()) {
                position++;

                final long releaseTime = upcomingEpisodes.getLong(NotificationQuery.EPISODE_FIRST_RELEASE_MS);
                if (releaseTime <= latestTimeToInclude) {
                    /*
                     * Only add those after the last one the user cleared.
                     * At most those of the last 24 hours (see query above).
                     */
                    if (releaseTime > latestTimeCleared) {
                        notifyPositions.add(position);
                    }
                } else {
                    // Too far into the future, stop!
                    break;
                }
            }

            // Notify if we found any episodes
            if (notifyPositions.size() > 0) {
                // store latest air time of all episodes we notified about
                upcomingEpisodes.moveToPosition(notifyPositions.get(notifyPositions.size() - 1));
                long latestAirtime = upcomingEpisodes.getLong(NotificationQuery.EPISODE_FIRST_RELEASE_MS);
                if (!AndroidUtils.isHoneycombOrHigher()) {
                    /*
                     * Everything below HC does not have delete intents, so
                     * we just never notify about the same episode twice.
                     */
                    Timber.d("Delete intent NOT supported, setting last cleared to: " + latestAirtime);
                    prefs.edit().putLong(NotificationSettings.KEY_LAST_CLEARED, latestAirtime).commit();
                }
                Timber.d("Found " + notifyPositions.size() + " new episodes, setting last notified to: "
                        + latestAirtime);
                prefs.edit().putLong(NotificationSettings.KEY_LAST_NOTIFIED, latestAirtime).commit();

                onNotify(upcomingEpisodes, notifyPositions, latestAirtime);
            }

            /*
             * Plan next episode to notify about, calc wake-up alarm as
             * early as user wants.
             */
            upcomingEpisodes.moveToPosition(-1);
            while (upcomingEpisodes.moveToNext()) {
                final long releaseTime = upcomingEpisodes.getLong(NotificationQuery.EPISODE_FIRST_RELEASE_MS);
                if (releaseTime > latestTimeToInclude) {
                    // store next episode we plan to notify about
                    Timber.d("Storing next episode time to notify about: " + releaseTime);
                    prefs.edit().putLong(NotificationSettings.KEY_NEXT_TO_NOTIFY, releaseTime).commit();

                    // calc actual wake up time
                    wakeUpTime = TimeTools.getEpisodeReleaseTime(this, releaseTime).getTime()
                            - DateUtils.MINUTE_IN_MILLIS * notificationThreshold;

                    break;
                }
            }
        }

        upcomingEpisodes.close();
    }

    // Set a default wake-up time if there are no future episodes for now
    if (wakeUpTime <= 0) {
        wakeUpTime = System.currentTimeMillis() + 6 * DateUtils.HOUR_IN_MILLIS;
        Timber.d("No future episodes found, wake up in 6 hours");
    }

    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(this, NotificationService.class);
    PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
    Timber.d("Going to sleep, setting wake-up alarm to: " + wakeUpTime);
    if (AndroidUtils.isKitKatOrHigher()) {
        am.setExact(AlarmManager.RTC_WAKEUP, wakeUpTime, pi);
    } else {
        am.set(AlarmManager.RTC_WAKEUP, wakeUpTime, pi);
    }
}

From source file:com.z3r0byte.magistify.Services.BackgroundService.java

public void cancelAlarm(Context context) {
    Intent intent = new Intent(context, BackgroundService.class);
    PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmManager.cancel(sender);
}

From source file:com.actinarium.nagbox.service.NagboxService.java

private void rescheduleAlarm() {
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    // Prepare pending intent. Setting, updating, or cancelling the alarm - we need it in either case
    Intent intent = new Intent(this, NagAlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    long nextTimestamp = NagboxDbOps.getClosestNagTimestamp(mDatabase);
    if (nextTimestamp == 0) {
        alarmManager.cancel(pendingIntent);
    } else {//from w  w w  . j a  va 2 s  .co  m
        // todo: deal with exact/inexact reminders later
        if (Build.VERSION.SDK_INT >= 23) {
            alarmManager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, nextTimestamp, pendingIntent);
        } else if (Build.VERSION.SDK_INT >= 19) {
            alarmManager.setWindow(AlarmManager.RTC_WAKEUP, nextTimestamp, ALARM_TOLERANCE, pendingIntent);
        } else {
            alarmManager.set(AlarmManager.RTC_WAKEUP, nextTimestamp, pendingIntent);
        }
    }
}

From source file:com.notalenthack.blaster.CommandActivity.java

private void cancelStatusUpdate() {
    // Setup expiration if we never get a message from the service
    AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent();
    intent.setAction(Constants.ACTION_REFRESH_STATUS);
    PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

    am.cancel(pi);
}

From source file:indrora.atomic.irc.IRCService.java

/**
 * Check status of service/*from  ww  w. j a  v a 2s.c o  m*/
 */
public void checkServiceStatus() {
    boolean shutDown = true;
    ArrayList<Server> mServers = Atomic.getInstance().getServersAsArrayList();
    int mSize = mServers.size();
    Server server;

    for (int i = 0; i < mSize; i++) {
        server = mServers.get(i);
        if (server.isDisconnected() && !server.mayReconnect()) {
            int serverId = server.getId();
            synchronized (this) {
                IRCConnection connection = connections.get(serverId);
                if (connection != null) {
                    connection.dispose();
                }
                connections.remove(serverId);
            }

            synchronized (alarmIntentsLock) {
                // XXX: alarmIntents can be null
                PendingIntent pendingRIntent = alarmIntents.get(serverId);
                if (pendingRIntent != null) {
                    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
                    am.cancel(pendingRIntent);
                    alarmIntents.remove(serverId);
                }
                ReconnectReceiver receiver = alarmReceivers.get(serverId);
                if (receiver != null) {
                    unregisterReceiver(receiver);
                    alarmReceivers.remove(serverId);
                }
            }
        } else {
            shutDown = false;
        }
    }

    if (shutDown) {
        foreground = false;
        stopForegroundCompat(R.string.app_name);
        stopSelf();
    }
}

From source file:org.jamienicol.episodes.AutoRefreshHelper.java

public void rescheduleAlarm() {
    NetworkStateReceiver.disable(context);

    final AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    final Intent intent = new Intent(context, AutoRefreshHelper.Service.class);
    final PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);

    if (getAutoRefreshEnabled() && getAutoRefreshPeriod() != 0) {
        final long alarmTime = getPrevAutoRefreshTime() + getAutoRefreshPeriod();

        Log.i(TAG, String.format("Scheduling auto refresh alarm for %d.", alarmTime));

        alarmManager.set(AlarmManager.RTC, alarmTime, pendingIntent);
    } else {//  w  w  w. j ava 2  s .  co  m
        Log.i(TAG, "Cancelling auto refresh alarm.");

        alarmManager.cancel(pendingIntent);
    }
}