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

问题描述 投票:1回答:2

我的问题是我从第三方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);
    }
android android-intent notifications alarmmanager android-pendingintent
2个回答
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);
}

© www.soinside.com 2019 - 2024. All rights reserved.