You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Android中设置指定日期与时间的通知?

实现指定日期时间触发通知的解决方案

没错,你猜的完全正确!要让通知在指定的日期和时间触发,核心就是把目标时间转换为从1970年1月1日00:00:00 UTC开始计算的毫秒级时间戳,然后将这个时间戳传给AlarmManager的set方法即可。下面结合你的代码给出具体实现步骤:

1. 将指定日期时间转换为毫秒时间戳

你可以用两种方式来构建目标时间并转成毫秒:

方式一:使用Calendar(兼容所有Android版本)

比如你想设置在2024年10月5日14:30:00触发通知:

// 构建目标日期时间
Calendar targetCalendar = Calendar.getInstance();
targetCalendar.set(Calendar.YEAR, 2024);
targetCalendar.set(Calendar.MONTH, Calendar.OCTOBER); // 月份从0开始,Calendar.OCTOBER对应10月
targetCalendar.set(Calendar.DAY_OF_MONTH, 5);
targetCalendar.set(Calendar.HOUR_OF_DAY, 14);
targetCalendar.set(Calendar.MINUTE, 30);
targetCalendar.set(Calendar.SECOND, 0);
targetCalendar.set(Calendar.MILLISECOND, 0);

// 转换为毫秒时间戳
long targetTimeInMillis = targetCalendar.getTimeInMillis();

方式二:使用LocalDateTime(Android 8.0+ 推荐,更简洁)

如果你的项目最低API版本在26及以上,可以用Java 8的日期时间API:

import java.time.LocalDateTime;
import java.time.ZoneId;

// 构建目标日期时间
LocalDateTime targetDateTime = LocalDateTime.of(2024, 10, 5, 14, 30, 0);
// 转换为毫秒时间戳(指定系统默认时区)
long targetTimeInMillis = targetDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();

2. 修改你的onClick方法

把原来的10秒延迟逻辑替换成目标时间戳即可,同时注意Android 12及以上版本对PendingIntent的flag要求,需要添加PendingIntent.FLAG_IMMUTABLE或FLAG_MUTABLE:

public void onClick(View view) {
    Intent intent = new Intent(getActivity(), ReminderBroadcast.class);
    // 适配Android 12+的PendingIntent flag
    int pendingIntentFlag = PendingIntent.FLAG_IMMUTABLE;
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), 0, intent, pendingIntentFlag);

    AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);

    // 这里替换成你计算好的目标时间戳
    Calendar targetCalendar = Calendar.getInstance();
    targetCalendar.set(2024, Calendar.OCTOBER, 5, 14, 30, 0);
    targetCalendar.set(Calendar.MILLISECOND, 0);
    long targetTimeInMillis = targetCalendar.getTimeInMillis();

    // 先判断目标时间是否在当前时间之后,避免立刻触发
    long currentTime = System.currentTimeMillis();
    if (targetTimeInMillis <= currentTime) {
        Toast.makeText(getActivity(), "设置的时间已过期,请重新选择", Toast.LENGTH_SHORT).show();
        return;
    }

    // 使用AlarmManager.RTC触发,基于系统墙钟时间
    alarmManager.set(AlarmManager.RTC, targetTimeInMillis, pendingIntent);

    OpenThis(view);
}

额外注意事项

  • 对于Android 6.0及以上设备,系统的休眠优化可能会影响AlarmManager的触发精度,如果需要精确触发,可以考虑使用setExact或setExactAndAllowWhileIdle(后者可在设备休眠时触发,但要注意不要滥用,避免消耗过多电量)。
  • 如果需要重复触发通知,可以使用setRepeating或setExactRepeating方法,但要注意Android 7.0+对重复闹钟的频率限制。

内容的提问来源于stack exchange,提问作者Кирилл Химов

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 21:42:59