我让用户设置一个重复警报的开始和结束时间,例如每天下午2:30到4:30。我可以将警报设置为在指定的启动时间启动,但如何在结束时停止它?
我想我应该在广播接收类中处理这个问题,在这个类中,我会得到额外的信息,并将其与系统时间进行比较,但我不能像在活动中取消警报那样取消警报。
这是我如何设置警报的一个例子:
Intent intent = new Intent(NewSchedule.this, RepeatingAlarm.class);
intent.putExtra("endTime", cal_alarmend.getTimeInMillis()/1000);
PendingIntent sender = PendingIntent.getBroadcast(NewSchedule.this, REQUEST_CODE, intent, 0);
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, cal_alarmstart.getTimeInMillis(), 6000, sender);接受者班:
public class RepeatingAlarm extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "repeating_received", Toast.LENGTH_SHORT).show();
long now = System.currentTimeMillis();
Bundle b = intent.getExtras();
long end = b.getLong("endTime");
Log.i("now", now + "");
Log.i("end", end + "");
if (now > end)
{
???????
}
}
}编辑
为什么我不能取消onReceive()中BroadcastReceiver中的警报?
public class RepeatingAlarm extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "repeating_received", Toast.LENGTH_SHORT).show();
long now = System.currentTimeMillis();
Bundle b = intent.getExtras();
long end = b.getLong("endTime");
int rc = b.getInt("reqCode");
Log.i("rc", rc + "");
long n = now/1000;
long e = end;
Log.i("now", n + "");
Log.i("end", e + "");
if (n > e)
{
Log.i("STATUS", "now > end " + n + ">" + e);
Intent intentstart = new Intent();
PendingIntent senderstart = PendingIntent.getBroadcast(context, rc, intentstart, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
am.cancel(senderstart);
}
else
{
Log.i("STATUS", "now <= end " + n + "<=" + e);
}
}
}我重复了堆栈跟踪,rc和我用来启动警报的请求代码完全一样。
这是堆栈跟踪:

在此之后,警报应该被取消,但我仍然收到祝酒词。
发布于 2012-10-14 14:10:22
我不能像在活动中取消警报那样取消这里的警报。
AFAIK你可以。更准确地说,我不认为会有什么问题。
我就是这样在活动中取消警报的
这段代码设置了警报。它不会取消它。若要取消警报,请在等效的PendingIntent (除了额外的)上创建一个类型相同(例如,getBroadcast())的Intent,并在AlarmManager上调用cancel()。
https://stackoverflow.com/questions/12882261
复制相似问题