从服务类中取消AlarmReceiver

时间:2014-05-08 06:02:34

标签: android service alarmmanager

我有一个用alaram Manager调用myService的类。从mainActivity这是我设置警报管理器的代码。

Intent downloader = new Intent(context, AlarmReceiver.class);
                downloader.putExtra("limit", limit.getSelectedItem().toString());
                downloader.putExtra("delay",perMin.getSelectedItem().toString());
                downloader.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);    `pendingIntent = PendingIntent.getBroadcast(context, 0, downloader,PendingIntent.FLAG_CANCEL_CURRENT);
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
int delay = Integer.parseInt(perMin.getSelectedItem().toString());
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,10 * 1000, delay * 1000, pendingIntent);

这里是我的报警接收器类 公共类AlarmReceiver扩展了BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    Intent update = new Intent(context, IntervalService.class);
    Log.i(tag, "Call service from Alaram Receiver");
    context.startService(update);
}}

我知道当我想从主要活动中取消报警管理器时,可以轻松调用alarmManager.cancel(pendingIntent),但我想取消报警管理器以完成我的服务任务,之后再次设置如上所述。

1 个答案:

答案 0 :(得分:3)

刚刚修改了你的代码,

public void setAlarmManager(boolean cancel){

PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,downloader,PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
int delay = Integer.parseInt(perMin.getSelectedItem().toString());
if(!cancel)
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,10 * 1000, delay * 1000, pendingIntent);
else
alarmManager.cancel(pendingIntent);

}

在需要时调用此函数,

开始:setAlarmManager(false);

取消:setAlarmManager(true); //在服务中调用此函数

试试,这可能有效。感谢。