0
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);
}
4

2 回答 2

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
            }
        }
    }
于 2013-10-26T19:51:04.113 回答
0

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

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

请解释您的代码的目的。

于 2013-10-26T19:48:54.560 回答