Как установить правильное время будильника / уведомления в Android? - PullRequest
1 голос
/ 27 марта 2019

Моя проблема в том, что я получаю данные о датах выпуска видеоигр от стороннего API, а эти даты от стороннего API в миллисекундах. Когда я использую класс Calendar в Java для установки своих будильников, будильник / уведомление вызывается в Неправильное время, как лучше настроить будильники в Android, чтобы они всегда вызывались в нужное время?

Например, код, который у меня сейчас есть, странный. Релизы игры в эту пятницу, я поставил будильник для этой игры в пятницу и в этот четверг в 8 вечера по восточному времени, будильник / уведомление срабатывает. Почему он не срабатывает в полночь пятницы?

Вот мой метод setAlarm

    /**
     * Sets the next alarm to run. When the alarm fires,
     * the app broadcasts an Intent to this WakefulBroadcastReceiver.
     */
    public void setAlarm(Context context, Alarm alarm) {
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        // Passing our intent data
        Intent alarmIntent = new Intent(context, AlarmReceiver.class);
        alarmIntent.putExtra("releaseId", alarm.getReleaseID());
        alarmIntent.putExtra("gameName", alarm.getGameName());
        alarmIntent.putExtra("gameId", alarm.getGameId());
        alarmIntent.putExtra("releaseDate", alarm.getDate());
        alarmIntent.putExtra("type", alarm.getType());
        // Note the release id is used here
        String alarmId = String.valueOf(alarm.getReleaseID()) + getTypeId(alarm.getType());
        PendingIntent pendingIntent  = PendingIntent.getBroadcast(context, Integer.parseInt(alarmId), alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        TimeZone timeZone = TimeZone.getTimeZone("UTC");
        Calendar calendar = Calendar.getInstance(timeZone);
        calendar.setTimeInMillis(alarm.getDate());
        Date date = calendar.getTime();
        alarmManager.set(AlarmManager.RTC_WAKEUP, date.getTime(), pendingIntent);
    }

Ответы [ 2 ]

0 голосов
/ 28 марта 2019

Попробуйте использовать григорианский календарь https://developer.android.com/reference/java/util/GregorianCalendar.html

0 голосов
/ 28 марта 2019

после android 4.4 используйте setExact ; после android 6.0 пользователь setExactAndAllowWhileIdle ссылка https://developer.android.google.cn/training/monitoring-device-state/doze-standby.html#restrictions https://developer.android.google.cn/about/versions/android-4.4.html#BehaviorAlarms

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, date.getTime(), pendingIntent);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    alarmManager.setExact(AlarmManager.RTC_WAKEUP, date.getTime(), pendingIntent);
} else {
    alarmManager.set(AlarmManager.RTC_WAKEUP, date.getTime(), pendingIntent);
}
...