我正在尝试从警报管理器中删除警报,该警报正在使用挂起的意图进行广播,并且使用广播接收器来捕获并执行该过程,正在调用deleteReminder函数,但意图仍在触发在时机成熟时.如果代码有问题,请告诉我.
I am trying to delete a alarm from the alarm manager which is using a pending intent to broadcast, and a broadcast receiver is used to catch and carry out the process,the deleteReminder function is getting called, but the intent is still firing when the time comes. If there is something wrong in the code please let me know.
public class ReminderManager { private Context mContext; private AlarmManager mAlarmManager; private Intent i; public ReminderManager(Context context) { mContext = context; mAlarmManager = (AlarmManager) context .getSystemService(Context.ALARM_SERVICE); } public void setReminder(Long taskId, Calendar when) { System.out.println("setReminder Called"); i = new Intent(mContext, Receiver.class); i.putExtra(Database.KEY_ROWID, (long) taskId); Toast.makeText(mContext, "setReminder" + Fragment.uniqueId, Toast.LENGTH_SHORT).show(); PendingIntent pi = PendingIntent.getBroadcast(mContext, Fragment.uniqueId, i, PendingIntent.FLAG_ONE_SHOT); mAlarmManager.set(AlarmManager.RTC_WAKEUP, when.getTimeInMillis(), pi); } public void deleteReminder(int uniqueID) { System.out.println("deleteReminder Called"); i = new Intent(mContext, Receiver.class); i.putExtra(Database.KEY_ROWID, (long) uniqueID); Toast.makeText(mContext, "deleteReminder" + uniqueID, Toast.LENGTH_SHORT).show(); PendingIntent.getBroadcast(mContext, uniqueID, i, PendingIntent.FLAG_UPDATE_CURRENT).cancel(); mAlarmManager.cancel(PendingIntent.getBroadcast(mContext, uniqueID, i, PendingIntent.FLAG_UPDATE_CURRENT)); } } 推荐答案我在setReminder函数中添加了一个布尔值以检查是否要删除,并在if语句中添加或删除了警报管理器中的警报,它减小了代码的大小,并且可以正常工作.
I added a boolean to the setReminder function to check if i want to delete or not, and a if statement to add or delete the alarm from the alarm manager, it reduced the size of the code and is working properly.
public class ReminderManager { private Context mContext; private AlarmManager mAlarmManager; private Intent i; // Constructor to set the context and set the alarmManager public ReminderManager(Context context) { mContext = context; mAlarmManager = (AlarmManager) context .getSystemService(Context.ALARM_SERVICE); } // used to create a pending intent using task id and Calendar object public void setReminder(Long taskId, Calendar when, boolean delete) { System.out.println("setReminder Called"); i = new Intent(mContext, OnAlarmReceiver.class); i.putExtra(NotesDatabase.KEY_ROWID, (long) taskId); Toast.makeText(mContext, "setReminder" + AddFragment.uniqueId, Toast.LENGTH_SHORT).show(); // broadcast !! // change the PendingIntent pi = PendingIntent.getBroadcast(mContext, AddFragment.uniqueId, i, PendingIntent.FLAG_ONE_SHOT); if(delete == false){ mAlarmManager.set(AlarmManager.RTC_WAKEUP, when.getTimeInMillis(), pi); }else{ pi.cancel(); mAlarmManager.cancel(pi); } }更多推荐
删除待处理的意图
发布评论