9

我使用鬧鐘從服務器獲取數據。 我喜歡讓用戶選擇啓動和停止鬧鐘。 這意味着我必須檢查並查看是否已設置警報。 我發現一些代碼,告訴我如果報警已被設置:Android AlarmManager設置和重置鬧鐘的問題

Intent I = new Intent(getApplicationContext(),AlarmReceiver.class); 
PendingIntent P = PendingIntent.getBroadcast(getApplicationContext(), 0, I, PendingIntent.FLAG_NO_CREATE); 
found = (P!=null); 

如果報警已設置我取消,但如果沒有設置它,然後我把它(如切換)

問題是這個作品只有一次。第一次檢查現有報警 的代碼將返回空值,表示沒有報警,但是在我取消報警後,一旦它返回指針 變爲某些值但報警未運行。

這裏是設置報警

am = (AlarmManager) getSystemService(getApplicationContext().ALARM_SERVICE); 
Intent I = new Intent(getApplicationContext(),AlarmReceiver.class); 
PendingIntent P = PendingIntent.getBroadcast(getApplicationContext(), 0, I, PendingIntent.FLAG_CANCEL_CURRENT); 
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 60000, P); 

代碼,這裏是取消報警代碼:

am = (AlarmManager) getSystemService(getApplicationContext().ALARM_SERVICE); 
Intent I = new Intent(getApplicationContext(),AlarmReceiver.class); 
PendingIntent P = PendingIntent.getBroadcast(getApplicationContext(), 0, I, PendingIntent.FLAG_CANCEL_CURRENT); 
am.cancel(P); 

我是在取消報警後復位東西,使它的PendingIntent走開。

+1

我真的不知道爲什麼你正在執行的檢查,看是否報警已經存在。你能解釋你的推理嗎? – 2011-02-10 23:06:51

+0

我想要一個按鈕作爲開關的開關。如果由於應用程序崩潰而導致我的鬧鐘設置丟失,請使用該按鈕作爲指示器。當用戶點擊小部件時,我使用警報來更新小部件,它會打開一個活動,用戶可以看到警報是否設置。我擔心的是在設置鬧鐘後,它將被關閉,用戶不知道該鬧鐘已關閉。 – Kemal 2011-02-11 17:22:51

回答

49

取消AlarmManager時,請勿使用帶有標誌FLAG_CANCEL_CURRENTPendingIntent。 相反,取消PendingIntent取消報警後明確:

am = (AlarmManager) getSystemService(getApplicationContext().ALARM_SERVICE); 
Intent i = new Intent(getApplicationContext(),AlarmReceiver.class); 
PendingIntent p = PendingIntent.getBroadcast(getApplicationContext(), 0, i, 0); 
am.cancel(p); 
p.cancel();