【问题标题】:Android AlarmManager Constantly goes offAndroid AlarmManager 不断关闭
【发布时间】:2012-09-17 21:54:24
【问题描述】:

我正在为我的计时器使用 AlarmManager。我有2节课。

在第一堂课 (MainActivity) 中,我使用下一个代码开始闹钟:

public void startAlarm(long Seconds) {
    Intent myIntent = new Intent(MainActivity.this, MyAlarmService.class);
    pendingIntent = PendingIntent.getService(MainActivity.this, 13141337,
            myIntent, 0);
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.add(Calendar.SECOND, (int) Seconds);
    alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
            pendingIntent);
}

在另一个类 (AlarmSound) 中,闹钟响起并且手机振动,我正在调用我的取消闹钟方法。

public void stopAlarm(){
    Intent intentstop = new Intent(AlarmSound.this, MyAlarmService.class);
    PendingIntent senderstop = PendingIntent.getBroadcast(AlarmSound.this,
            13141337, intentstop, 0);
    AlarmManager myalarm = (AlarmManager) getSystemService(ALARM_SERVICE);
    myalarm.cancel(senderstop);
    Log.w("Karl","stopAlarm?");
}

这是正确的方法吗?因为我的闹钟在 android 4.1 上不断响起。

提前致谢!

【问题讨论】:

    标签: android alarmmanager


    【解决方案1】:

    您的取消不起作用。待处理的 Intent 必须匹配 - 因为它们有不同的上下文(MainActivity 和 AlarmSound),所以取消将不起作用。您还必须在两者上都使用 getService 。 你可以

    a) 尝试重新创建匹配的待处理 Intent

    b) 在Service中获取启动Service的pendingIntent并用它来取消

    但如果您不使用 setRepeating(),通常每个警报只会响一次。

    您确定您正在使用 stopself() 正确终止您的服务并在 onStartCommand() 方法中为其提供正确的标志吗?

    【讨论】:

    • 谢谢你的回答,我不使用 setRepeating 有问题吗?我只使用上面的代码来启动我的闹钟。我也不使用 stopself 和 onStartCommand。我认为我正确终止了?我怎样才能确定这一点?我的 MainActivity 中有另一个 stopAlarm 方法,效果很好。我很确定(通过测试等)如何在我的 AlarmSound 中使用 stopAlarm?
    • 您能否发布完整的 AlarmSound 代码?
    • 我使用 pastebin 是因为我无法回答我自己的代码,pastebin.com/cnxY8mH5 你去吧
    • 我的错,我以为你会直接调用活动。当您调用 finish() 并重新打开时,您的服务可能仍在调用 AlarmSound Activity。在启动 AlarmSound 后尝试在您的服务中调用 stopself() - 或尝试将初始 AlarmManager 设置为启动 AlarmSound 而不是您的服务。如果您需要更多帮助,我也可以使用您的服务的 pastebin。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多