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);
}
答案 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)
你没有解释你希望这个代码做什么,所以我们真的不知道,但这些是我看到的一些错误:
ReminderService
是Service
的子类,因此您应该使用PendingIntent.getService
而不是PendingIntent.getBroadcast
。setRepeatig
= 0调用intervalMillis
,并且从不调用AlarmManager.cancel
,我猜这是一个错误,因为Android不会触发您的警报永远,不停。请解释您的代码的目的。