报警应用程序不准确

时间:2016-01-06 16:56:56

标签: android android-intent alarmmanager android-alarms

我正在为Android创建一个警报应用程序,由于某种原因,我的警报总会有20-60秒的延迟。我不知道为什么它会发生,因为我使用API​​ 19 +的

的setExact()方法

我的代码:

beforeOpen

警报接收器

private void setAlarm() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        mHour = mTimePicker.getHour();
        mMinutes = mTimePicker.getMinute();
    } else {
        mHour = mTimePicker.getCurrentHour();
        mMinutes = mTimePicker.getCurrentMinute();
    }

    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, mHour);
    calendar.set(Calendar.MINUTE, mMinutes);

    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    Intent alarmIntent = new Intent(EditAlarm.this, AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(EditAlarm.this, 0, alarmIntent, 0);


    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
    } else {
        alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
    }

}

警报活动

public class AlarmReceiver extends WakefulBroadcastReceiver {

public AlarmReceiver() {
}

@Override
public void onReceive(final Context context, Intent intent) {

    Toast.makeText(context, "Alarm works", Toast.LENGTH_LONG).show();
    Intent alarmIntent = new Intent(context, AlarmActivity.class);
    alarmIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(alarmIntent);
}

我做错了什么?在此先感谢;)

1 个答案:

答案 0 :(得分:3)

要解决此问题,您还需要设置秒数。您需要将其设置为零,以便在指定的分钟到达时触发它:

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, mHour);
calendar.set(Calendar.MINUTE, mMinutes);
calendar.set(Calendar.SECOND, 0);