我在使用 AlarmManager 时遇到了问题,我设置了用于安排重复警报的代码,并且在我运行应用程序后,警报运行正常。即使我单击主页按钮(并且应用程序已暂停),警报仍会按其间隔运行。
问题是如果我打开任务管理器并强制关闭应用程序,那么警报就会停止运行。
这是正常行为吗,有什么办法可以避免这种情况并在关闭应用程序后保持警报运行?
代码如下 - 该方法由 ApplicationContext 类 onCreate() 调用。
private void scheduleAlarm() {
if (alarmScheduled == true) { return; } // we only need to schedule once.
int alarmInterval = Def.pref(getApplicationContext()).getInt("alarmInterval", 30);
final Intent intent = new Intent(getApplicationContext(), CollectorAlarmReceiver.class);
final PendingIntent pending = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);
AlarmManager alarmMgr = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmMgr.cancel(pending); // cancel others.
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+1000,
alarmInterval*1000, pending);
Def.log(TAG,"scheduleAlarm(): alarm scheduled, interval: "+alarmInterval+" seconds");
alarmScheduled = true;
}
收货人代码:
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "CollectorAlarmReceiver invoked, starting CollectorService in background");
context.startService(new Intent(context, CollectorService.class));
Intent collectorService = new Intent(context,CollectorService.class);
collectorService.putExtra("action", CollectorService.ACTION_BACKGROUND_REQUEST_MESSAGES);
context.sendBroadcast(collectorService);
}
谢谢!