How i can cancel an alarm after a period of time? | android

▼魔方 西西 提交于 2019-12-13 05:13:17

问题


hi i have an alarm here and i want a way to cancel it AFTER a period of time like a day for example or a week ,,, and thanks in advance ,,

    am = (AlarmManager)parent.getContext().getSystemService(Context.ALARM_SERVICE);

     //the title and the description of the notification



    Intent alarmintent = new Intent(parent.getContext(), Alarm_Receiver.class);
     alarmintent.putExtra("title",titlePills + dea22);
      alarmintent.putExtra("note",dea22);
     alarmintent.putExtra("NOTIFICATION_ID",String.valueOf(CountMultipleAlarm));
     //HELLO_ID is a static variable that must be initialized at the BEGINNING OF CLASS with 1;

      //example:protected static int HELLO_ID =1;
      PendingIntent sender = PendingIntent.getBroadcast(parent.getContext(), CountMultipleAlarm,
                                     alarmintent,0);

      //VERY IMPORTANT TO SET FLAG_UPDATE_CURRENT... this will send correct extra's informations to 
       //AlarmReceiver Class
         // Get the AlarmManager service
        am.setRepeating(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(), 11000, sender);
                                     intentArray.add(sender);

回答1:


You have already set an alarm once, so you know how to do it. The key is to set a second alarm, whose purpose is to end the original alarm. The difficult part is finding the original alarm to cancel, however, you can just execute this code upon your second alarm to cancel the first, using the cancel pending intent. This code, as Android docs specify, will cancel all alarms with the same class. Thus, you only need to create an intent, pass it to the AlarmManager, and you can cancel the alarm.

Intent alarmintent = new Intent(parent.getContext(), Alarm_Receiver.class);
PendingIntent sender = PendingIntent.getBroadcast(parent.getContext(), CountMultipleAlarm,
                                 alarmintent,0);
am.cancel(sender);



回答2:


try

final PendingIntent sender = PendingIntent.getBroadcast(parent.getContext(), CountMultipleAlarm,
                                     alarmintent,0);
int someTime=1000;

new Handler().postDelayed(new Runnable()
{
    public void run()
    {
     am.cancel(sender);
    }
}, someTime);



回答3:


Set a second alarm that cancels the first alarm.



来源:https://stackoverflow.com/questions/20635518/how-i-can-cancel-an-alarm-after-a-period-of-time-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!