2011-12-07 68 views
1

我正在使用AlarmManagerNotificationManagerBroadcastReceiver。 當我使用特定日期設置鬧鐘時,該鬧鐘第一次工作。但是,當我修改日期並單擊確認按鈕時,警報立即在任何日期 中運行。我想在固定的時間之後設置過期日期之後的鬧鐘時間間隔。 它有什麼問題?我目前不明白。Android報警,當我更改日期時運行任何日期的通知

confirmButton.setOnClickListener(new View.OnClickListener() 
{ 
    public void onClick(View v) { 
    //set alarm with expiration date     
    am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 
    setOneTimeAlarm(); 
    Toast.makeText(fridgeDetails.this, "Alarm automatic set", 
     Toast.LENGTH_SHORT).show(); 
    setResult(RESULT_OK); 
    finish(); 
} 

public void setOneTimeAlarm() { 
    c.set(Calendar.HOUR_OF_DAY, 14); 
    c.set(Calendar.MINUTE, 49); 
    c.set(expiredYear, expiredMonth, expiredDay); 
    Intent myIntent = new Intent(fridgeDetails.this, AlarmService.class); 
    PendingIntent pendingIntent = PendingIntent.getBroadcast(
     fridgeDetails.this, 0, myIntent, PendingIntent.FLAG_ONE_SHOT); 
    am.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), 
     AlarmManager.INTERVAL_DAY, pendingIntent); 
} 
}); 

AlarmService.java

public class AlarmService extends BroadcastReceiver{ 
    NotificationManager nm; 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     nm = (NotificationManager) context.getSystemService(
      Context.NOTIFICATION_SERVICE); 
     CharSequence from = "Check your fridge"; 
     CharSequence message = "It's time to eat!"; 
     PendingIntent contentIntent = PendingIntent.getActivity(context, 0, 
      new Intent(), 0); 
     Notification notif = new Notification(R.drawable.ic_launcher, 
      "Keep Fridge", System.currentTimeMillis()); 
     notif.setLatestEventInfo(context, from, message, contentIntent); 
     notif.defaults |= Notification.DEFAULT_SOUND; 
     notif.flags |= Notification.FLAG_AUTO_CANCEL; 
     nm.notify(1, notif); 
    } 
} 
+0

這不會解決你的問題,但在我看來,在這種情況下使用FLAG_ONE_SHOT並不理想,因爲它只允許從AlarmManager進行一次回調。嘗試使用0代替。 –

回答

2

您需要設置的屬性,而不是FLAG_ONE_SHOT。這是針對單次鬧鈴事件而不是重複。試試這個

PendingIntent pendingIntent = PendingIntent.getBroadcast(
     fridgeDetails.this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT); 

看到更多細節從here

編輯:

當你的PendingIntent通知做

PendingIntent contentIntent = PendingIntent.getActivity(context, 0,new Intent(), 0); 

在此傳遞意圖的空對象當您點擊通知時,您需要爲該類傳遞類名稱在設定鬧鐘時間你做

Intent myIntent = new Intent(fridgeDetails.this, AlarmService.class); 
PendingIntent pendingIntent = PendingIntent.getBroadcast(
     fridgeDetails.this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT); 

現在只是在意向通過胡亞蓉名稱,比如假設你要啓動您的家庭活動和活動名稱,比如「homeactivity」

PendingIntent contentIntent = PendingIntent.getActivity(context, 0,new Intent(context,HomeActivity.class), 0); 
+0

非常感謝!我還有一個問題,如果我點擊通知,它不會打開已存在的應用程序。我點擊通知圖標時如何打開? – wholee1

+0

查看編輯答案帖子 – Pratik

+0

之後,我該如何調用contentIntent? – wholee1