在过去的两天里,我一直试图让 AlarmManager 取消我之前设置的警报,但由于某种原因我无法让它工作。
我已经用谷歌搜索了这个问题,最常见的解决方案是跟踪旧意图,因为只有那些,它们才能被取消。
为了解决这个问题,我决定创建自己的 Intent 类,它是可序列化的。
然后我将 Intent 类保存到一个“Intent.ser”文件中,并调用那些来取消我的警报。
SerUitvalIntent.java
public class SerUitvalIntent extends Intent implements Serializable
{
private String klas;
private int delay;
private Boolean uitvalBuzz;
private Boolean algemeenBuzz;
public SerUitvalIntent(Context context, Class<?> class1)
{
super(context, class1);
}
public void setBundle(Bundle b)
{
klas = b.getString(someClass.KLAS);
delay = b.getInt(someClass.DELAY);
uitvalBuzz = b.getBoolean(someClass.UITVALBUZZ);
algemeenBuzz = b.getBoolean(someClass.ALGEMEENBUZZ);
}
public Bundle getBundle()
{
Bundle b = new Bundle();
b.putBoolean(someClass.UITVALBUZZ, uitvalBuzz);
b.putBoolean(someClass.ALGEMEENBUZZ, algemeenBuzz);
b.putString(someClass.KLAS, klas);
b.putInt(someClass.DELAY, delay);
return b;
}
/**
*
*/
private static final long serialVersionUID = 8289838097824161902L;
}
someClass.java
public static void schedule(Context context, long delay, Bundle data, Boolean startup)
{
DataHandler dHandle = new DataHandler(context, false);
final AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
SerUitvalIntent oldIntent = dHandle.getAlarm();
if(oldIntent != null)
{
oldIntent.putExtra(BUNDLE, oldIntent.getBundle());
oldIntent.putExtra(FROMUI, false);
Bundle b = oldIntent.getBundle();
Log.i("AlarmManagerUitval", "Cancelled " + b.getString(KLAS) + "." + b.getInt(DELAY) + "." + b.getBoolean(UITVALBUZZ) + " alarm");
final PendingIntent oldPending = PendingIntent.getService(context, 0, oldIntent, 0);
//Cancel latest alarm
alarm.cancel(oldPending);
}
final SerUitvalIntent intent = new SerUitvalIntent(context, UitvalService.class);
intent.setBundle(data);
dHandle.setAlarm(intent);
intent.putExtra(BUNDLE, data);
intent.putExtra(FROMUI, false);
final PendingIntent pending = PendingIntent.getService(context, 0, intent, 0);
Log.i("AlarmManagerUitval", "Started " + data.getString(KLAS) + "." + data.getInt(DELAY) + "." + data.getBoolean(UITVALBUZZ) + " alarm");
long time;
if(startup)
{
time = SystemClock.elapsedRealtime();
}
else
{
time = SystemClock.elapsedRealtime()+delay;
}
alarm.setRepeating(AlarmManager.ELAPSED_REALTIME, time,delay, pending);
}
我的 Logcat 在设置和取消警报时显示相同的数据(Log.i() 显示相同的数据),但不知何故它不会取消。
Logcat 数据
05-26 14:21:00.108: I/AlarmManagerUitval(26041): Started v4.60000.true alarm
05-26 14:21:00.178: I/UitvalService(26041): updating: v4
(...)
05-26 14:21:30.227: I/AlarmManagerUitval(26041): Cancelled v4.60000.true alarm
05-26 14:21:30.237: I/AlarmManagerUitval(26041): Started h4.60000.true alarm
05-26 14:21:30.307: I/UitvalService(26041): updating: h4
(...)
05-26 14:22:30.526: I/UitvalService(26104): updating: v4
05-26 14:23:30.244: I/UitvalService(26104): updating: v4