调用setAlarm方法期间调用的Alarm BroadcastReceiver的onReceive()

时间:2013-10-27 06:47:22

标签: android

新手在这里,我有这个功能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方法并显示警报。为什么呢?

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

中的第二个参数
ala.set(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(), pi);

是指定何时首先触发警报。在您的代码中,您在从共享首选项中读取时触发它。如果该时间已经过去,则立即触发警报。这可能是调用onReceive()方法的一个原因。

检查您所阅读的时间是否是将来的某个时间。