2013-10-27 14 views
0

新手,我有這個功能setAlarm的onReceive()在這裏稱爲

public void setAlarm(){ 


     SharedPreferences sa=PreferenceManager.getDefaultSharedPreferences(getBaseContext()); 


     int hr=sa.getInt("alarmhour", 6); 
     int mn=sa.getInt("alarmminute", 0); 
     String st1=sa.getString("alarmstatus", "Alarm Disabled"); 

     if(st1.equals("Alarm Enabled")) 
     { 

     AlarmManager ala = (AlarmManager)getSystemService(Context.ALARM_SERVICE); 
     Intent inte = new Intent(this, epicalarm.class); 
     PendingIntent pi = PendingIntent.getBroadcast(this, 0, inte, 0); 


     Calendar time = Calendar.getInstance(); 
     time.set(Calendar.HOUR_OF_DAY, hr); 
     time.set(Calendar.MINUTE, mn); 
     time.set(Calendar.SECOND, 0); 

     ala.set(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(), pi); 
     } 




} 

我每次調用該函數setAlarm,該onReceive方法被調用並顯示報警。爲什麼?

回答

0

ala.set(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(), pi); 

第二個參數是指定何時第一觸發報警。在您的代碼中,您從您的共享首選項中讀取時觸發它。如果該時間已經過去,則立即觸發警報。這可能是onReceive()方法被調用的原因之一。

檢查您閱讀的時間是否將來有一段時間。

+0

是的,這是真的,它只發生在時間已經過去了,我不能停止嗎? – AcidBurn

+0

不,我不這麼認爲。你爲什麼要設置鬧鐘已經過去了? –

+0

假設當前時間是11:00,並且用戶想要設置爲10:00,我希望第二天觸發警報,而不是立即觸發警報... – AcidBurn

1
Calendar calendar = Calendar.getInstance(); 
calendar.setTimeInMillis(System.currentTimeMillis());  
calendar.set(Calendar.HOUR_OF_DAY, h);   
calendar.set(Calendar.MINUTE, m);   
calendar.set(Calendar.SECOND, 0);   
calendar.set(Calendar.MILLISECOND,0); 
// if values of h and m are less than current time 
//then 'if' block will executes and adds the amount of days as 1 to your calendar object. 
if (calendar.before(Calendar.getInstance())) 
{ 
    calendar.add(Calendar.DATE, 1); 
} 

//you will get an alarm` after a day instead of now 

ala.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pi);