这段代码做什么用的?为什么我的警报没有停止?

时间:2013-10-26 18:53:41

标签: android alarmmanager

Intent in2 = new Intent(context, ReminderService.class);
PendingIntent pendingIntent2 = PendingIntent.getBroadcast(context, 0, in2, 0);
AlarmManager alarmManager2 = (AlarmManager)context.getSystemService(context.ALARM_SERVICE);
alarmManager2.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5 * 1000), 0, pendingIntent2);

并且reminderservice.java包含以下代码

public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);
    Context context = getApplicationContext();
    Intent in = new Intent(this, RemindBroadcastReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, in, 0);
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5 * 1000), 1000, pendingIntent);
}

2 个答案:

答案 0 :(得分:1)

首先,我建议你只使用 RemindBroadcastReceiver 。不需要 ReminderService

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5 * 1000), 1000, pendingIntent);

这里设置了每1秒钟后触发的重复警报。您需要使用 alarmManager.set而不是alarmManager.setRepeating

我认为以下代码对您有所帮助:

 /------------------- CALLING PART
        Intent in2 = new Intent("MY_ALARM_ACTION");
        PendingIntent pendingIntent2 = PendingIntent.getBroadcast(this, 0, in2, 0);
        AlarmManager alarmManager2 = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
        //alarmManager2.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5 * 1000), pendingIntent2);
       alarmManager2.setRepeating(AlarmManager.RTC_WAKEUP,
            System.currentTimeMillis() + (5 * 1000), AlarmManager.INTERVAL_DAY, pendingIntent2);
}
/-------------------



/-------------------------- RemindBroadcastReceiver ----------------
    public class RemindBroadcastReceiver extends BroadcastReceiver
    {
        @Override
        public void onReceive(Context context, Intent intent)
        {
            if (intent.getAction() == "MY_ALARM_ACTION")
            {
                // TODO Enter your code here
            }
        }
    }

答案 1 :(得分:0)

你没有解释你希望这个代码做什么,所以我们真的不知道,但这些是我看到的一些错误:

  • 我认为ReminderServiceService的子类,因此您应该使用PendingIntent.getService而不是PendingIntent.getBroadcast
  • 在第一段代码中,您使用参数setRepeatig = 0调用intervalMillis,并且从不调用AlarmManager.cancel,我猜这是一个错误,因为Android不会触发您的警报永远,不停。
  • 您为什么要启动服务,以便设置另一个警报以触发其他内容?

请解释您的代码的目的。