Android AlarmManager 设定过去的时间会触发事件

Android AlarmManager 设定过去的时间会触发事件

在使用 AlarmManager 做每日定时任务时,发现如果设定的时间小于当前的系统时间,那么设定后会立刻收到一次定时任务回调。

我们设想的是设定的时间应该是明日的这个时间,但是如果打印出设定的时间会发现,设定的时间是今天的。

java 复制代码
public void addTask() {
        Calendar calendar = Calendar.getInstance();
        // 设置时区,否则会有 8 个小时的时间差
        calendar.setTimeZone(TimeZone.getDefault());

        calendar.set(Calendar.HOUR_OF_DAY, 15);
        calendar.set(Calendar.MINUTE, 30);
        calendar.set(Calendar.SECOND, 0);

        long setTime = calendar.getTimeInMillis();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        Log.e("WillWolf", "setTime-->" + sdf.format(new Date(setTime)));
        long currentTime = System.currentTimeMillis();
        Log.e("WillWolf", "currentTime-->" + sdf.format(new Date()));

        alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTime().getTime(), "TAG", listener, null);
    }

日志输出为:

java 复制代码
setTime-->2024-06-21 15:30:00
currentTime-->2024-06-21 17:31:02

所以,为了避免时间已经过去还引发回调,可以添加一个时间判断。

java 复制代码
public void addTask() {
        Calendar calendar = Calendar.getInstance();
        // 设置时区,否则会有 8 个小时的时间差
        calendar.setTimeZone(TimeZone.getDefault());

        calendar.set(Calendar.HOUR_OF_DAY, 15);
        calendar.set(Calendar.MINUTE, 30);
        calendar.set(Calendar.SECOND, 0);

        long setTime = calendar.getTimeInMillis();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        Log.e("WillWolf", "setTime-->" + sdf.format(new Date(setTime)));
        long currentTime = System.currentTimeMillis();
        Log.e("WillWolf", "currentTime-->" + sdf.format(new Date()));
        // 如果当前的时间大于设定的时间,表明设定的时间是未来一天的,做一个加一天的操作
        if (currentTime >= setTime) {
            calendar.add(Calendar.HOUR, 24);
            setTime = calendar.getTimeInMillis();
            Log.e("WillWolf", "setTime tomorrow-->" + sdf.format(new Date(setTime)));
        }

        alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTime().getTime(), "TAG", listener, null);
    }

日志输出为:

java 复制代码
setTime-->2024-06-21 15:30:00
currentTime-->2024-06-21 17:31:02
setTime tomorrow-->2024-06-22 15:30:00

这样设定的触发时间就是明天的了。

相关推荐
小孔龙2 小时前
GraphicBuffer 跨进程共享
android
行业研究员2 小时前
Android内置GPS与腾讯地图定位技术对比分析
android·android定位·腾讯地图定位
Android-Flutter3 小时前
android WMS 详解(二)
android·kotlin
游戏开发爱好者84 小时前
App Store 上传 IPA 自动化,.p8 密钥认证与 CI/CD 接入实战
android·运维·ci/cd·小程序·uni-app·自动化·iphone
游戏开发爱好者85 小时前
iOS 推送怎么配置,APNs 推送证书、设备库与群发
android·ios·小程序·https·uni-app·iphone·webview
阿pin5 小时前
Android随笔-kotlin 高阶函数
android·kotlin·高阶函数
wxson728220 小时前
【Android视频监控系统技术总结】
android·音视频
hunterandroid21 小时前
[Android 从零到一] LiveData 粘性事件与单次消费:从重复触发到可靠事件总线
android
hunterandroid21 小时前
[Android 从零到一] Android 事件分发机制:从 ACTION_DOWN 到 View 事件消费链路
android