【问题标题】:Android: Resetting repeating AlarmManager from within called serviceAndroid:从被调用的服务中重置重复的 AlarmManager
【发布时间】:2013-11-07 01:07:19
【问题描述】:

我在服务上设置了重复警报,并决定从被调用的服务中重置警报最方便。原因是该服务已经有代码来检查它是否在用户定义的时间表(时间范围)内。当它超出时间范围时,它会将警报重置为在用户选择的未来时间开始。也许我处理错了,但我会把这个问题放在那里,看看你的想法。

活动通过创建重复警报来启动服务:

//Activity
Calendar cal = Calendar.getInstance();
Intent intent = new Intent(getApplicationContext(), MyService.class);
intent.setData(Uri.parse("MyService://identifier"));
PendingIntent pIntent = PendingIntent.getService(getApplicationContext(), 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(ALARM_SERVICE);
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
            intervalInMins*60000, pIntent);

服务有这样的东西:

//Service
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Uri Action = intent.getData();
    try {
        if (Action.equals(Uri.parse("MyService://identifier"))) {
            //Simplifying the code here: CalculatedOffset is determined from the current time
            //and scheduled start time. intervalInMins is read from settings.
            if (!WithinSchedule()) {
                Calendar cal = Calendar.getInstance();
                PendingIntent pIntent = PendingIntent.getService(getApplicationContext(), 0, intent, 0);
                AlarmManager alarm = (AlarmManager)getSystemService(ALARM_SERVICE);
                alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis() + CalculatedOffset,
                        intervalInMins*60000, pIntent);
            }
        }
    } catch (NullPointerException np) {
        np.printStackTrace();
    }
    return Service.START_REDELIVER_INTENT;
}

我希望重新使用意图来重置重复警报。使用这个新代码,我看到多个警报在开始时间到来时连续快速触发。它不应该像那样乱跑,而是应该像调度重置之前那样定期触发。我需要在调试器中捕获它,但还不能确定确切的条件。我对警报的理解完全在这里吗?有没有更好的方法来做到这一点?

附录:其中的一个问题是我正在使用 RootTools 来获得超级用户权限,以便绕过 Android 4.2 的飞行模式。在调度之前这不是问题,但我怀疑 su 是否在警报叠加时阻塞了很长时间。

【问题讨论】:

  • 我想知道,在替换重复警报时,创建PendingIntent时是否需要使用PendingIntent.FLAG_CANCEL_CURRENT?我一直用0。

标签: android service alarmmanager alarm repeat


【解决方案1】:

在接收警报的服务中重用意图确实有效。我已经从使用重复警报切换到单次警报,每次调用服务时都会重新设置警报。不幸的是,这并没有解决警报堆叠的问题。罪魁祸首肯定是su阻塞。它可能是 RootTools 或 su 本身。我需要将库从 2.6 更新到 3.x,看看是否有什么不同。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-04
    • 1970-01-01
    • 2012-06-10
    • 1970-01-01
    • 2014-06-25
    • 2012-06-13
    • 1970-01-01
    相关资源
    最近更新 更多