0

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

4

2 回答 2

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);
于 2017-07-07T15:01:48.243 回答
0

中的第二个参数

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

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

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

于 2013-10-27T06:56:20.480 回答