如何在Android中设置正确的警报/通知时间?

时间:2019-03-27 16:30:42

标签: android android-intent notifications alarmmanager android-pendingintent

我的问题是我从第三方api获取视频游戏发布日期数据,并且第三方api的日期以毫秒为单位,当我使用java的Calendar类设置警报时,警报/通知会在错误的时间,在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 :(得分:0)

在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);
}

答案 1 :(得分:-1)