android - Android平台有类似iOS本地Notification的等效解决方案吗?

标签 android ios notifications alarmmanager uilocalnotification

我的应用需要在未来的某个指定时间(可能几个月后)向用户显示通知。在 iOS 中,我需要做的就是:

UILocalNotification* localNotification = [[UILocalNotificationalloc] init]; 
localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:60];
localNotification.alertBody = @"Your alert message";
localNotification.timeZone = [NSTimeZone defaultTimeZone];
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];

然而,在Android中,它比我原先预期的要复杂得多:

  1. 我必须使用 Alarm Manager 安装警报,以便在将来的每个指定时间启动服务。

  2. 这些服务依次创建通知,并使用 Notification Manager 将通知推送到状态栏等。

但是这个方案有问题:

  1. 如果设备在警报响起之前重新启动,则警报将丢失。我可以注册开机播like this并重新安装服务。但是,我真的很想避免为同一事件安装重复的警报,但似乎无法从警报管理器获取当前安装的警报?
  2. 通知是在未来的预定时间(比如一个月后)编写的,而不是在我设置通知时(现在)。届时,通知所需的数据可能不再可用。除了存储相关数据并等待警报响起外,我看不出有任何解决办法。

Android 上的本地通知问题有无痛解决方案吗?

最佳答案

If the device is restarted before the alarm fires, the alarm is lost. I can register for boot-up broadcast like this and re-install the services. However, I really want to avoid installing duplicate alarms for the same event, but it seems there is no way to get currently installed alarms from the Alarm Manager?

当设备重启时,您将如何获得重复的警报?当设备重新启动时,所有警报都被取消,所以你会像你说的那样在设备启动时在 BroadcastReceiver 中再次启动它

The notification is composed at the scheduled time in future (say a month later), not when I set the notification(now). At that time, the required data for the notification may no longer be available. I don't see any way around this, except to store the relevant data, and wait for the alarm to fire.

没错,您需要存储要在通知中显示的数据,SharedPreferences 可能是最简单的

编辑:

您不需要保留对未决 Intent 的引用,您所要做的就是以相同的方式创建 Intent 示例

当你第一次创建你使用这个 Intent 的警报时

Intent intent = new Intent(context,MyClass.class);
    //any flags or extras

PendingIntent.getBroadcast(context, 0, intent, 0);

现在您想取消该警报,因此只需再次创建相同的 Intent ,它必须是原始的 1 对 1

Intent intent = new Intent(context,MyClass.class);
    //any flags or extras that you previously had

PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);

alarmMgr.cancel(pi);

关于android - Android平台有类似iOS本地Notification的等效解决方案吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27490329/

相关文章:

android - Kivy:跨平台通知图标

安卓获取当前位置

java - StateListDrawable 切换滤色器

java - api 29 的源代码无法下载?

Android:在后台运行应用程序

ios - 每天不同时间本地通知

java - 如何在 android.webkit.WebView(s) 之间共享缓存,包括 cookie

ios - 在一个按钮中使用 segue 和 IBAction

android - 使用 NSURLSession 将 Android post 请求转换为 iOS swift

Objective-C:超出十六进制值模式的正则表达式