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

Android AlarmManager应用后台时不触发PendingIntent问题求助

Android预约前一天定时推送提醒实现方案

我们的应用需要在预约前一天的指定时间向用户推送提醒通知,可通过以下方案实现:利用Calendar配置触发时间,通过PendingIntent关联负责通知构建的NotifyService,最后借助AlarmManager在指定时间触发该PendingIntent。

设置闹钟的核心代码

private void setAlarm(Long dateInMillies, String testGroup, int i) {

    AlarmManager am = (AlarmManager) getApplicationContext().
            getSystemService(Context.ALARM_SERVICE);

    Log.d("TAG", "setAlarm: Called ");
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(dateInMillies);
    calendar.add(Calendar.DAY_OF_MONTH, -2);
    calendar.set(Calendar.HOUR_OF_DAY,14);
    calendar.set(Calendar.MINUTE, 50);
    calendar.set(Calendar.SECOND, 0);


    int scheduleNumber = i + 1;

    Intent intent = new Intent(getApplicationContext(), NotifyService.class);
    intent.putExtra(NotifyService.INTENT_NOTIFY, true);
    intent.putExtra("event", testGroup);
    intent.putExtra("scheduleNumber", scheduleNumber);
    intent.putExtra("date", dateInMillies);

    PendingIntent pendingIntent = PendingIntent.
            getService(getApplicationContext(),
                    scheduleNumber,
                    intent,
                    PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);


    if (am != null) {
        am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
        Log.d("DateTime", "setAlarm: Time in milis "+calendar.getTimeInMillis());
    }
}

关键逻辑说明

  • 时间校准:基于传入的预约时间戳dateInMillies初始化Calendar实例,通过add(Calendar.DAY_OF_MONTH, -2)将日期调整为预约前两天(若需求为预约前一天,可将参数改为-1),随后固定触发时间为14:50:00
  • PendingIntent配置:使用getService创建绑定NotifyService的PendingIntent,以scheduleNumber作为唯一请求码,避免多个预约提醒的Intent相互覆盖;FLAG_IMMUTABLE保证Intent不可变,符合Android 12及以上版本的安全规范,FLAG_UPDATE_CURRENT确保更新后的Extra参数能被正确传递
  • 闹钟触发策略:调用setExactAndAllowWhileIdle实现精准触发,该方法支持在设备低电量空闲状态下正常执行;RTC_WAKEUP模式会在触发时唤醒设备,确保通知能及时推送给用户

内容的提问来源于stack exchange,提问作者Aniket Dhanrao

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 07:27:55