我有AlarmManager的問題,我設置了用於安排重複報警的代碼,在運行應用程序後,報警運行良好。即使我點擊主頁按鈕(並且應用程序已暫停),警報仍會按其間隔運行。關閉應用程序後Android報警被取消
問題是如果我打開任務管理器並強制關閉應用程序,則警報停止運行。
這是一個正常的行爲,有沒有什麼辦法可以避免這種情況,關閉應用程序後保持警報運行?
代碼如下 - 該方法由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);
}
謝謝!
你可以發佈你的接收器代碼和一個alarmInterval的例子嗎? – ninjasense 2011-01-10 06:20:45
我發佈了Receiver的代碼。 alarmInterval是30秒。你可以看到onReceive中有一個Log,所以我可以跟蹤Receiver被調用的時間。在運行應用程序時,它可以正常工作,問題在於它關閉時。 – 2011-01-10 06:54:43
爲什麼不在系統默認時鐘中設置鬧鐘?然後通過任務管理器殺死它,看看它是否像你的應用程序一樣。如果它也不能警告你。我認爲你的應用程序可以,你不需要做任何事情。 – 2013-08-21 22:02:11