How to cancel PendingIntent at specific time?

十年热恋 提交于 2019-12-12 00:12:30

问题


AlarmManager works perfectly when I have not declared cancel but do not fire when I declare the cancel.. Here is the code:

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:

 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! :)


回答1:


Change the line am1.cancel(pi); to am1.cancel(pi1); - you're cancelling the original 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). 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;



来源:https://stackoverflow.com/questions/10321880/how-to-cancel-pendingintent-at-specific-time

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