[英]onReceive() of Alarm BroadcastReceiver called during setAlarm method is called
新手在這里,我有這個功能setAlarm
:
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
方法並顯示警報。 為什么?
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);
中的第二個參數
ala.set(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(), pi);
指定何時首先觸發警報。 在您的代碼中,您將在從共享的首選項中讀取信息時觸發它。 如果已經過去了,警報將立即觸發。 這可能是調用onReceive()方法的原因之一。
檢查您閱讀的時間是否是將來的某個時間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.