无法取消警报并以新数据开始(警报管理器)

时间:2017-05-03 08:34:59

标签: android alarmmanager

我有一个在后台运行的类notifer。它每1分钟后重新启动一次。 oncece of notifer是:

@Override
public void onReceive(final Context contextn, final Intent intent)
{
    Log.d("Notifier","started");
    String id[] = intent.getStringArrayExtra("id");
    Log.d("notifier",String.valueOf(id.length));

    if (id!=null) {
        context = contextn;
        backgroundsync back = new backgroundsync();
        back.execute(id);

        Intent callagain = new Intent(context, notifer.class);
        callagain.putExtra("id", id);
        PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, callagain, 0);
        AlarmManager notifalm;
        notifalm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        notifalm.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 60000, alarmIntent);
    }
}

每当notifer需要处理的数据发生变化时,我会在检测到数据更改时从UI线程执行此操作。

cancelalarm();
//changed data in database here
setalarm();

方法定义是:

private void setalarm()
{
    Intent callagain = new Intent(this,notifer.class);
    String ids[]=interact.checked();
    for (int i=0;i<ids.length;i++)
        Log.d("Main checked new",ids[i]);
    callagain.putExtra("id", ids);
    alarmIntent = PendingIntent.getBroadcast(this, 0, callagain, 0);
    AlarmManager notifalm;
    notifalm = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
    notifalm.setExact(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),alarmIntent);
}
private void cancelalarm()
{
    Intent callagain = new Intent(this,notifer.class);
    String ids[]=interact.checked();
    for (int i=0;i<ids.length;i++)
        Log.d("Main checked old",ids[i]);
    callagain.putExtra("id", ids);
    alarmIntent = PendingIntent.getBroadcast(this, 0, callagain, 0);
    AlarmManager notifalm;
    notifalm = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
    notifalm.cancel(alarmIntent);
}

interact.checked()返回需要发送给notifer的数据库中的数据。

问题是即使数据发生变化,notifer仍然会继续处理旧数据。请帮忙,我被困在这里几个小时。

如果您需要任何其他信息,请与我们联系。

1 个答案:

答案 0 :(得分:0)

现在必须用这个替换pendingIntent语句。

alarmIntent = PendingIntent.getBroadcast(context, 0, callagain, PendingIntent.FLAG_CANCEL_CURRENT);

从这里开始:https://stackoverflow.com/a/17570455/7732470