简体   繁体   English

如何在特定时间取消PendingIntent?

[英]How to cancel PendingIntent at specific time?

AlarmManager works perfectly when I have not declared cancel but do not fire when I declare the cancel .. Here is the code: 当我未声明cancel时,AlarmManager可以完美工作,但是当我声明cancel时,不触发。

Calendar c= Calendar.getInstance();
                c.set(Calendar.HOUR_OF_DAY, 0); 
                c.set(Calendar.MINUTE, 37);
                c.set(Calendar.SECOND, 0);

            Toast.makeText(this, c.getTime().toString(), Toast.LENGTH_LONG).show();
        intent = new Intent(TestAlarm.this, TestAlarmService.class);
        pi = PendingIntent.getService(TestAlarm.this, 1, intent, 0);
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        am.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pi);

and cancel code: cancel代码:

 c.add(Calendar.HOUR_OF_DAY, 0);
        c.add(Calendar.MINUTE, 38);
        c.add(Calendar.SECOND, 0);
        PendingIntent pi1=PendingIntent.getService(TestAlarm.this, 1, intent, 0);
        AlarmManager am1 = (AlarmManager) getSystemService(ALARM_SERVICE);
        //stopService(intent);
        am1.cancel(pi);

Now here I want to start my AlarmManager to go off at 12:37 and cancel after one or two minutes...But Whenever I use cancel code the AlarmManager never fires... Thanks in Advance! 现在,我要在12:37开始启动我的AlarmManager ,并在一到两分钟后cancel ...但是只要我使用cancel代码, AlarmManager不会触发...在此AlarmManager感谢! :) :)

Change the line am1.cancel(pi); 更改行am1.cancel(pi); to am1.cancel(pi1); am1.cancel(pi1); - you're cancelling the original PendingIntent -您要取消原始的PendingIntent

Also, in your cancel code, you're calling c.add() (which add on to the current date/time) instead of c.set() (which explicitly sets the next date/time). 另外,在您的取消代码中,您要调用c.add() (添加到当前日期/时间),而不是c.set() (显式设置下一个日期/时间)。 By calling c.add(Calendar.MINUTE, 38) , you're actually adding 38 minutes to the current Calendar, instead of setting the time to 12:38; 通过调用c.add(Calendar.MINUTE, 38) ,实际上是在当前日历中添加38分钟,而不是将时间设置为12:38;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM