【问题标题】:Is it possible to set an Android Notification or a later date and time that will fire when the app is not running?是否可以设置 Android 通知或应用程序未运行时将触发的稍后日期和时间?
【发布时间】:2026-01-14 22:15:01
【问题描述】:

从我读到的内容看来,这样的代码似乎需要应用程序在线程中运行,直到通知触发。我需要在稍后的日期和时间触发通知,以便用户看到通知就像任何其他通知一样,然后单击它并打开一个活动,传递一些数据以便应用知道该做什么。

如何在应用程序不一直运行的情况下让此通知在几天后触发?

我是否使用等待来完成此操作?

long millis = 60000;
myNotification.wait(millis);

这是我的代码,它会立即触发

NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(getActivity())
.setSmallIcon(R.drawable.star)
.setContentTitle("How was " + me.getString("EventTitle") + "?")
.setContentText("Click here to leave your review");

Intent resultIntent = new Intent(getActivity(), SetupActivity.class);

PendingIntent resultPendingIntent =
PendingIntent.getActivity(
getActivity(),
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);

    mBuilder.setContentIntent(resultPendingIntent);

    int mNotificationId = me.getInt("EventID");
    // Gets an instance of the NotificationManager service
    NotificationManager mNotifyMgr = 
            (NotificationManager) getActivity().getSystemService(getActivity().NOTIFICATION_SERVICE);


    // Builds the notification and issues it.
    mNotifyMgr.notify(mNotificationId, mBuilder.build());

【问题讨论】:

  • 不,你通常会使用AlarmManager
  • 好的,AlarmManager 也会产生同样风格的通知,就像你在安卓手机上下拉屏幕顶部时看到的推送通知?
  • AlarmManager 安排 PendingIntent 执行。通常,您会将 PendingIntent 设为创建通知的 BroadcastReceiver

标签: java android notifications


【解决方案1】:

正如 A--C 所写,使用AlarmManager 安排PendingIntent 在您想要的时间被调用。您可能会使用RTC_WAKEUP 警报,意思是“时间基于System.currentTimeMillis(),如Calendar 使用”和“让我们将设备从睡眠模式中唤醒”。使用广播PendingIntent,并且您的Notification 代码可以进入onReceive() 方法,如果您不需要执行任何磁盘或网络I/O 来获取用于Notification 本身的信息。

请注意,在 Android 4.4 中,AlarmManager 的规则发生了一些变化。您需要在 Android 4.4+ 上使用 setExact(),在早期 Android 版本上使用 set()

【讨论】:

  • 您可以这样安排多个通知吗?如果设备重启会怎样?
  • @PaulG:“你能以这种方式安排多个通知吗?” - 当然。 “如果设备重新启动会怎样?” -- AlarmManager 已被清除,您需要重新建立警报。
最近更新 更多