Android闹钟在运行但不在秒时为零?

时间:2015-09-24 10:19:08

标签: java android alarmmanager android-alarms

我正在制作闹钟应用程序。报警运行正常。例如,如果我在 06:00 PM 设置闹钟,则会在 06:00 PM 执行。问题是当秒正好为零时警报没有执行。有时它会在32秒(下午06:00:32)运行,有时会在其他时间等运行。

在我的主要活动中,我设置了闹钟保存按钮,当我点击时,执行以下代码:

buttonSetAlarm.setOnClickListener(new View.OnClickListener(){

        @Override
        public void onClick(View arg0) {
            Calendar current = Calendar.getInstance();

            Calendar cal = Calendar.getInstance();
            cal.set(pickerDate.getYear(),
                    pickerDate.getMonth(),
                    pickerDate.getDayOfMonth(),
                    pickerTime.getCurrentHour(),
                    pickerTime.getCurrentMinute(),
                    00);

            if(cal.compareTo(current) <= 0){
                //The set Date/Time already passed
                Toast.makeText(getApplicationContext(),
                        "Invalid Date/Time",
                        Toast.LENGTH_LONG).show();
            }else{
                setAlarm(cal);
            }

        }});

主要活动中的SetAlarm方法是:

private void setAlarm(Calendar targetCal){

    info.setText("\n\n***\n"
            + "Alarm is set@ " + targetCal.getTime() + "\n"
            + "***\n");

    Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, 0);
    AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), 1000*60, pendingIntent);
}

在我的AlarmReceiver BroadCastReceiver中,我有以下onReceive方法:

public void onReceive(Context context, Intent intent) {
    // TODO: This method is called when the BroadcastReceiver is receiving
    // an Intent broadcast.
    Toast.makeText(context, "Alarm received!", Toast.LENGTH_LONG).show();
}

关于我的问题应该在哪里的想法?

2 个答案:

答案 0 :(得分:1)

从API 19(KitKat)开始,默认情况下,警报不准确。如果您的targetSdkVersion设置为19或更高,则会使用此行为。请参阅AlarmManager.setRepeating()方法文档中的注释:

  

注意:从API 19开始,所有重复警报都不准确。如果您的应用程序需要精确的交付时间,那么它必须使用一次性精确警报,每次重新安排如上所述。 targetSdkVersion早于API 19的旧应用程序将继续将所有警报(包括重复警报)视为完全警报。

所以你最好的选择是使用精确的一次性警报,每次过期都会相应地再次设置警报。

答案 1 :(得分:1)

根据documentation

Note: Beginning with API 19 (KITKAT) alarm delivery is inexact: the OS will shift alarms in order to minimize wakeups and battery use. There are new APIs to support applications which need strict delivery guarantees; see setWindow(int, long, long, PendingIntent) and setExact(int, long, PendingIntent). Applications whose targetSdkVersion is earlier than API 19 will continue to see the previous behavior in which all alarms are delivered exactly when requested.