List of usage examples for android.app PendingIntent cancel
public void cancel()
From source file:opensource.zeocompanion.ZeoCompanionApplication.java
private void configAlarmManagerToPrefs() { // setup a daily alarm if auto-emailing is enabled SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); boolean enabledAutoEmail = prefs.getBoolean("email_auto_enable", false); boolean enabledDatabaseReplicate = prefs.getBoolean("database_replicate_zeo", false); long desiredTOD = prefs.getLong("email_auto_send_time", 0); // will default to midnight long configuredTOD = prefs.getLong("email_auto_send_time_configured", 0); // will default to midnight // determine whether there is an active AlarmManager entry that we have established AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE); Intent intentCheck = new Intent(this, ZeoCompanionApplication.AlarmReceiver.class); intentCheck.setAction(ZeoCompanionApplication.ACTION_ALARMMGR_WAKEUP_RTC); PendingIntent existingPi = PendingIntent.getBroadcast(this, 0, intentCheck, PendingIntent.FLAG_NO_CREATE); if (enabledAutoEmail || enabledDatabaseReplicate) { // Daily AlarmManager is needed if (existingPi != null && desiredTOD != configuredTOD) { // there is an existing AlarmManager entry, but it has the incorrect starting time-of-day; // so cancel it, and rebuild a new one Intent intent1 = new Intent(this, ZeoCompanionApplication.AlarmReceiver.class); intent1.setAction(ZeoCompanionApplication.ACTION_ALARMMGR_WAKEUP_RTC); PendingIntent pi1 = PendingIntent.getBroadcast(this, 0, intent1, PendingIntent.FLAG_CANCEL_CURRENT); am.cancel(pi1);/*from w ww. j a v a2 s. c o m*/ pi1.cancel(); existingPi = null; } if (existingPi == null) { // there is no existing AlarmManager entry, so create it Date dt = new Date(desiredTOD); Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, dt.getHours()); calendar.set(Calendar.MINUTE, dt.getMinutes()); calendar.set(Calendar.SECOND, dt.getSeconds()); Intent intent2 = new Intent(this, ZeoCompanionApplication.AlarmReceiver.class); intent2.setAction(ZeoCompanionApplication.ACTION_ALARMMGR_WAKEUP_RTC); PendingIntent pi2 = PendingIntent.getBroadcast(this, 0, intent2, PendingIntent.FLAG_UPDATE_CURRENT); am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi2); SharedPreferences.Editor editor = prefs.edit(); editor.putLong("email_auto_send_time_configured", desiredTOD); editor.commit(); } } else { // Daily AlarmManager is not needed if (existingPi != null) { // there is an AlarmManager entry pending; need to cancel it Intent intent3 = new Intent(this, ZeoCompanionApplication.AlarmReceiver.class); intent3.setAction(ZeoCompanionApplication.ACTION_ALARMMGR_WAKEUP_RTC); PendingIntent pi3 = PendingIntent.getBroadcast(this, 0, intent3, PendingIntent.FLAG_CANCEL_CURRENT); am.cancel(pi3); pi3.cancel(); } } }
From source file:com.android.deskclock.data.TimerModel.java
/** * Updates the callback given to this application from the {@link AlarmManager} that signals the * expiration of the next timer. If no timers are currently set to expire (i.e. no running * timers exist) then this method clears the expiration callback from AlarmManager. *//*w ww . jav a 2s . co m*/ private void updateAlarmManager() { // Locate the next firing timer if one exists. Timer nextExpiringTimer = null; for (Timer timer : getMutableTimers()) { if (timer.isRunning()) { if (nextExpiringTimer == null) { nextExpiringTimer = timer; } else if (timer.getExpirationTime() < nextExpiringTimer.getExpirationTime()) { nextExpiringTimer = timer; } } } // Build the intent that signals the timer expiration. final Intent intent = TimerService.createTimerExpiredIntent(mContext, nextExpiringTimer); if (nextExpiringTimer == null) { // Cancel the existing timer expiration callback. final PendingIntent pi = PendingIntent.getService(mContext, 0, intent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_NO_CREATE); if (pi != null) { mAlarmManager.cancel(pi); pi.cancel(); } } else { // Update the existing timer expiration callback. final PendingIntent pi = PendingIntent.getService(mContext, 0, intent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT); schedulePendingIntent(nextExpiringTimer.getExpirationTime(), pi); } }
From source file:at.ac.uniklu.mobile.sportal.service.MutingService.java
private void mute(int alarmId) { Log.d(TAG, "mute()"); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); if (Preferences.getLocationStatus(preferences) == Preferences.LOCATION_STATUS_WAITING) { Log.d(TAG, "mute() blocked - waiting for a location update"); return;//from w ww. j a va 2s.co m } // check if phone is already muted by the user AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE); boolean isPhoneAlreadyMuted = audioManager.getRingerMode() != AudioManager.RINGER_MODE_NORMAL && !Preferences.isMutingPeriod(preferences); if (isPhoneAlreadyMuted) { Log.d(TAG, "phone is already muted, scheduling next mute"); scheduleMute(true); return; } // load the current period from the db MutingPeriod mutingPeriod = null; Log.d(TAG, "muting period id: " + alarmId); if (DEBUG_WITH_FAKE_ALARMS) { mutingPeriod = new MutingPeriod(); mutingPeriod.setId(-1); mutingPeriod.setBegin(System.currentTimeMillis()); mutingPeriod.setEnd(mutingPeriod.getBegin() + 10000); mutingPeriod.setName("Fakeevent"); } else { mutingPeriod = Studentportal.getStudentPortalDB().mutingPeriods_getPeriod(alarmId); } // check if phone is located at university notifyUser(Studentportal.NOTIFICATION_MS_INFO, true, mutingPeriod.getName(), mutingPeriod.getName(), getString(R.string.automute_notification_course_started_locating)); boolean isPhoneLocationKnown = false; boolean isPhoneLocatedAtUniversity = false; String locationSource = null; WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE); if (wifiManager.isWifiEnabled()) { ScanResult scanResult = MutingUtils.findMutingWifiNetwork(wifiManager.getScanResults()); if (scanResult != null) { Log.d(TAG, "phone located by wifi: " + scanResult.SSID); isPhoneLocationKnown = true; isPhoneLocatedAtUniversity = true; locationSource = "wifi (" + scanResult.SSID + ")"; } } if (!isPhoneLocationKnown) { // phone location could not be determined by wifi, trying network location instead... LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { Intent locationIntent = new Intent("at.ac.uniklu.mobile.sportal.LOCATION_UPDATE") .putExtra(EXTRA_ALARM_ID, alarmId); PendingIntent pendingLocationIntent = PendingIntent.getBroadcast(this, 0, locationIntent, PendingIntent.FLAG_UPDATE_CURRENT); // remove the location receiver (so it doesn't get registered multiple times [could also happen on overlapping mute() calls) locationManager.removeUpdates(pendingLocationIntent); if (Preferences.getLocationStatus(preferences) == Preferences.LOCATION_STATUS_RECEIVED) { isPhoneLocationKnown = true; pendingLocationIntent.cancel(); Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (location == null) { Log.d(TAG, "location received but still null"); } else { MutingRegion mutingRegion = MutingUtils.findOverlappingMutingRegion(location); if (mutingRegion != null) { Log.d(TAG, "phone located by network @ " + mutingRegion.getName()); isPhoneLocatedAtUniversity = true; locationSource = "location (" + mutingRegion.getName() + ")"; } } } else { Log.d(TAG, "trying to locate the phone by network..."); // wait for a location update Preferences.setLocationStatus(preferences, Preferences.LOCATION_STATUS_WAITING); locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, pendingLocationIntent); return; // exit method - it will be re-called from the location broadcast receiver on a location update } } } boolean isAlwaysMuteEnabled = Preferences.isAutomuteWithoutLocation(this, preferences); if (isPhoneLocationKnown) { if (!isPhoneLocatedAtUniversity) { Log.d(TAG, "phone is not located at university, scheduling next mute"); scheduleMute(true); removeNotification(Studentportal.NOTIFICATION_MS_INFO); return; } } else { Log.d(TAG, "phone cannot be located"); if (!isAlwaysMuteEnabled) { Log.d(TAG, "alwaysmute is disabled, scheduling next mute"); Preferences.setLocationStatus(preferences, Preferences.LOCATION_STATUS_NONE); scheduleMute(true); removeNotification(Studentportal.NOTIFICATION_MS_INFO); return; } } // only turn the ringtone off if we aren't currently in a muting period. // if we are in a muting period the ringtone is already muted and the request should be ignored, // else rintoneTurnOn() won't turn the ringtone back on because ringtone override will be set to true if (!Preferences.isMutingPeriod(preferences)) { MutingUtils.ringtoneTurnOff(this); } // persist that from now on the phone is in a muting period Preferences.setMutingPeriod(preferences, true); // inform user via a notification that a course has started and the phone has been muted notifyUser(Studentportal.NOTIFICATION_MS_INFO, true, mutingPeriod.getName(), mutingPeriod.getName(), getString(R.string.automute_notification_course_muted)); final boolean isPhoneLocationKnownAnalytics = isPhoneLocationKnown; final String locationSourceAnalytics = locationSource; Analytics.onEvent(Analytics.EVENT_MUTINGSERVICE_MUTE, "isPhoneLocationKnown", isPhoneLocationKnownAnalytics + "", "locationSource", locationSourceAnalytics); scheduleUnmute(mutingPeriod.getEnd()); }
From source file:com.janacare.walkmeter.MainActivity.java
/** * Respond to "Start" button by requesting activity recognition * updates.//from w w w . j a va2 s. c om * @param view The view that triggered this method. */ public void onStopUpdates(View view) { // Check for Google Play services if (!servicesConnected()) { return; } /* * Set the request type. If a connection error occurs, and Google Play services can * handle it, then onActivityResult will use the request type to retry the request */ mRequestType = ActivityUtils.REQUEST_TYPE.REMOVE; PendingIntent pendingIntent = mDetectionRequester.getRequestPendingIntent(); if (pendingIntent == null) { Intent intent = new Intent(getApplicationContext(), ActivityRecognitionIntentService.class); pendingIntent = PendingIntent.getService(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); } if (pendingIntent != null) { // Pass the remove request to the remover object mDetectionRemover.removeUpdates(pendingIntent); /* * Cancel the PendingIntent. Even if the removal request fails, canceling the PendingIntent * will stop the updates. */ pendingIntent.cancel(); } // TODO: Update toggle button to "Start pedometer" }
From source file:com.janacare.walkmeter.MainActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); vPref = getApplicationContext().getSharedPreferences(ActivityUtils.SHARED_PREFERENCES, Context.MODE_PRIVATE); // Set the main layout requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); setContentView(R.layout.pedometer);//from ww w . j a va 2s . co m getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title); showStepsToday = (TextView) findViewById(R.id.tvStepsToday); showStepsYesterday = (TextView) findViewById(R.id.tvStepsYesterday); showStepsHighest = (TextView) findViewById(R.id.tvStepsHighest); btnCount = (Button) findViewById(R.id.btnCount); tvwindow_title = (TextView) findViewById(R.id.tvwindow_tite); tvtodayAfter = (TextView) findViewById(R.id.tvStepsTodayAfter); headToday = (TextView) findViewById(R.id.tvStepsToday1); headYesterday = (TextView) findViewById(R.id.tvStepsYesterday2); headHighest = (TextView) findViewById(R.id.tvStepsHighest3); Typeface regular = Typeface.createFromAsset(getAssets(), "Roboto-Regular.ttf"); Typeface thin = Typeface.createFromAsset(getAssets(), "Roboto-Thin.ttf"); tvwindow_title.setTypeface(regular); showStepsToday.setTypeface(thin); showStepsYesterday.setTypeface(thin); showStepsHighest.setTypeface(thin); tvtodayAfter.setTypeface(regular); headToday.setTypeface(regular); headYesterday.setTypeface(regular); headHighest.setTypeface(regular); btnCount.setTypeface(regular); int i = vPref.getInt(Constants.KEY_STEPS_TODAY, 0); int j = vPref.getInt("steps_yesterday", 0); int k = vPref.getInt("minutes_highest", i); Log.d("step in", Long.toString(i)); Log.d("show steps", "showStepsToday: " + showStepsToday); showStepsToday.setText(Integer.toString(i)); showStepsYesterday.setText(Integer.toString(j)); showStepsHighest.setText(Integer.toString(k)); mBroadcastManager = LocalBroadcastManager.getInstance(this); // Create a new Intent filter for the broadcast receiver mBroadcastFilter = new IntentFilter(ActivityUtils.ACTION_REFRESH_STATUS_LIST); mBroadcastFilter.addCategory(ActivityUtils.CATEGORY_LOCATION_SERVICES); // Get detection requester and remover objects mDetectionRequester = new DetectionRequester(this); mDetectionRemover = new DetectionRemover(this); // Create a new LogFile object mLogFile = LogFile.getInstance(this); btnCount.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Log.d(TAG, "before btn action" + vPref.getBoolean("btnFlag", false)); Editor editor = vPref.edit(); if (!vPref.getBoolean("btnFlag", false)) { Log.d(TAG, "first time btn pressed"); if (!servicesConnected()) { return; } mRequestType = ActivityUtils.REQUEST_TYPE.ADD; mDetectionRequester.requestUpdates(); btnCount.setText("Stop Counting"); editor.putBoolean("btnFlag", true); editor.commit(); Log.d(TAG, "" + vPref.getBoolean("btnFlag", false)); } else { Log.d(TAG, "in onClick after btn shows stop counting"); if (!servicesConnected()) { return; } mRequestType = ActivityUtils.REQUEST_TYPE.REMOVE; PendingIntent pendingIntent = mDetectionRequester.getRequestPendingIntent(); if (pendingIntent == null) { Intent intent = new Intent(getApplicationContext(), ActivityRecognitionIntentService.class); pendingIntent = PendingIntent.getService(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); } if (pendingIntent != null) { // Pass the remove request to the remover object mDetectionRemover.removeUpdates(pendingIntent); pendingIntent.cancel(); } editor.putBoolean("btnFlag", false); editor.commit(); btnCount.setText("Start Counting!"); } } }); }
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 w w w . j a va 2s .co m 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.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(); }/*from www.j a va 2s . co m*/ // 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:edu.mit.media.funf.probe.Probe.java
/** * Resets all of the run data information, and removes all requests *//* w w w .j ava2s.c o m*/ public void reset() { getHistoryPrefs().edit().clear().commit(); if (requestsIntent != null) { requestsIntent.removeExtra(INTERNAL_REQUESTS_KEY); } PendingIntent selfLaunchingIntent = PendingIntent.getService(this, 0, getRequestsIntent(), PendingIntent.FLAG_NO_CREATE); if (selfLaunchingIntent != null) { selfLaunchingIntent.cancel(); } }
From source file:org.ohmage.reminders.types.location.LocTrigService.java
private void cancelSamplingAlarm(String action) { Intent i = new Intent(action); PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, PendingIntent.FLAG_NO_CREATE); if (pi != null) { AlarmManager alarmMan = (AlarmManager) getSystemService(ALARM_SERVICE); alarmMan.cancel(pi);/* ww w. j ava2 s.c o m*/ pi.cancel(); } }
From source file:com.android.deskclock.data.TimerModel.java
/** * Updates the notification controlling unexpired timers. This notification is only displayed * when the application is not open./*from w ww . j a v a2s . c om*/ */ void updateNotification() { // Notifications should be hidden if the app is open. if (mNotificationModel.isApplicationInForeground()) { mNotificationManager.cancel(mNotificationModel.getUnexpiredTimerNotificationId()); return; } // Filter the timers to just include unexpired ones. final List<Timer> unexpired = new ArrayList<>(); for (Timer timer : getMutableTimers()) { if (timer.isRunning() || timer.isPaused()) { unexpired.add(timer); } } // If no unexpired timers exist, cancel the notification. if (unexpired.isEmpty()) { mNotificationManager.cancel(mNotificationModel.getUnexpiredTimerNotificationId()); return; } // Sort the unexpired timers to locate the next one scheduled to expire. Collections.sort(unexpired, Timer.EXPIRY_COMPARATOR); final Timer timer = unexpired.get(0); final long remainingTime = timer.getRemainingTime(); // Generate some descriptive text, a title, and some actions based on timer states. final String contentText; final String contentTitle; @DrawableRes int firstActionIconId, secondActionIconId = 0; @StringRes int firstActionTitleId, secondActionTitleId = 0; Intent firstActionIntent, secondActionIntent = null; if (unexpired.size() == 1) { contentText = formatElapsedTimeUntilExpiry(remainingTime); if (timer.isRunning()) { // Single timer is running. if (TextUtils.isEmpty(timer.getLabel())) { contentTitle = mContext.getString(R.string.timer_notification_label); } else { contentTitle = timer.getLabel(); } firstActionIconId = R.drawable.ic_pause_24dp; firstActionTitleId = R.string.timer_pause; firstActionIntent = new Intent(mContext, TimerService.class) .setAction(HandleDeskClockApiCalls.ACTION_PAUSE_TIMER) .putExtra(HandleDeskClockApiCalls.EXTRA_TIMER_ID, timer.getId()); secondActionIconId = R.drawable.ic_add_24dp; secondActionTitleId = R.string.timer_plus_1_min; secondActionIntent = new Intent(mContext, TimerService.class) .setAction(HandleDeskClockApiCalls.ACTION_ADD_MINUTE_TIMER) .putExtra(HandleDeskClockApiCalls.EXTRA_TIMER_ID, timer.getId()); } else { // Single timer is paused. contentTitle = mContext.getString(R.string.timer_paused); firstActionIconId = R.drawable.ic_start_24dp; firstActionTitleId = R.string.sw_resume_button; firstActionIntent = new Intent(mContext, TimerService.class) .setAction(HandleDeskClockApiCalls.ACTION_START_TIMER) .putExtra(HandleDeskClockApiCalls.EXTRA_TIMER_ID, timer.getId()); secondActionIconId = R.drawable.ic_reset_24dp; secondActionTitleId = R.string.sw_reset_button; secondActionIntent = new Intent(mContext, TimerService.class) .setAction(HandleDeskClockApiCalls.ACTION_RESET_TIMER) .putExtra(HandleDeskClockApiCalls.EXTRA_TIMER_ID, timer.getId()); } } else { if (timer.isRunning()) { // At least one timer is running. final String timeRemaining = formatElapsedTimeUntilExpiry(remainingTime); contentText = mContext.getString(R.string.next_timer_notif, timeRemaining); contentTitle = mContext.getString(R.string.timers_in_use, unexpired.size()); } else { // All timers are paused. contentText = mContext.getString(R.string.all_timers_stopped_notif); contentTitle = mContext.getString(R.string.timers_stopped, unexpired.size()); } firstActionIconId = R.drawable.ic_reset_24dp; firstActionTitleId = R.string.timer_reset_all; firstActionIntent = TimerService.createResetUnexpiredTimersIntent(mContext); } // Intent to load the app and show the timer when the notification is tapped. final Intent showApp = new Intent(mContext, HandleDeskClockApiCalls.class) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).setAction(HandleDeskClockApiCalls.ACTION_SHOW_TIMERS) .putExtra(HandleDeskClockApiCalls.EXTRA_TIMER_ID, timer.getId()) .putExtra(HandleDeskClockApiCalls.EXTRA_EVENT_LABEL, R.string.label_notification); final PendingIntent pendingShowApp = PendingIntent.getActivity(mContext, 0, showApp, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT); final NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext).setOngoing(true) .setLocalOnly(true).setShowWhen(false).setAutoCancel(false).setContentText(contentText) .setContentTitle(contentTitle).setContentIntent(pendingShowApp) .setSmallIcon(R.drawable.stat_notify_timer).setPriority(NotificationCompat.PRIORITY_HIGH) .setCategory(NotificationCompat.CATEGORY_ALARM).setVisibility(NotificationCompat.VISIBILITY_PUBLIC); final PendingIntent firstAction = PendingIntent.getService(mContext, 0, firstActionIntent, PendingIntent.FLAG_UPDATE_CURRENT); final String firstActionTitle = mContext.getString(firstActionTitleId); builder.addAction(firstActionIconId, firstActionTitle, firstAction); if (secondActionIntent != null) { final PendingIntent secondAction = PendingIntent.getService(mContext, 0, secondActionIntent, PendingIntent.FLAG_UPDATE_CURRENT); final String secondActionTitle = mContext.getString(secondActionTitleId); builder.addAction(secondActionIconId, secondActionTitle, secondAction); } // Update the notification. final Notification notification = builder.build(); final int notificationId = mNotificationModel.getUnexpiredTimerNotificationId(); mNotificationManager.notify(notificationId, notification); final Intent updateNotification = TimerService.createUpdateNotificationIntent(mContext); 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(mContext, 0, updateNotification, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT); final long nextMinuteChange = remainingTime % MINUTE_IN_MILLIS; final long triggerTime = SystemClock.elapsedRealtime() + nextMinuteChange; schedulePendingIntent(triggerTime, pi); } else { // Cancel the update notification callback. final PendingIntent pi = PendingIntent.getService(mContext, 0, updateNotification, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_NO_CREATE); if (pi != null) { mAlarmManager.cancel(pi); pi.cancel(); } } }