android - PendingIntent 与 IntentService 不起作用

标签 android alarmmanager android-pendingintent intentservice android-alarms

以下代码非常适合Activity:

Intent intent = new Intent(context, MyActivity.class);
PendingIntent operation = PendingIntent.getActivity(context, 
                              0, 
                              intent, 
                              PendingIntent.FLAG_UPDATE_CURRENT);
alarmmanager.setExact(AlarmManager.RTC_WAKEUP, 
                              startTime.getTimeInMillis(),
                              operation);

但是,当我对IntentService做同样的事情时,只有当startTime和我设置闹钟的时间在同一天时它才有效。例如如果我今天将闹钟设置为下午 5 点,它将被执行,但是当我今天将闹钟设置为明天下午 5 点时,它将不会被执行。如果这是Activity,那么这两种情况都适用。

Intent intent = new Intent(context, MyService.class);
PendingIntent operation = PendingIntent.getService(context, 
                              0, 
                              intent, 
                              PendingIntent.FLAG_UPDATE_CURRENT);
alarmmanager.setExact(AlarmManager.RTC_WAKEUP, 
                              startTime.getTimeInMillis(),
                              operation);

如何解决这个问题?

我想要实现的目标是每天在准确的时间执行 IntentService

最佳答案

The goal here I am trying to achieve is to execute IntentService every day at the exact time.

随着版本的不同,Google 的难度逐渐加大。请参阅Android AlarmManager setExact() is not exact 。对于您的情况,可能有两种方法可以解决此问题:

  1. 您启动一个 Activity ,该 Activity 会启动服务(因为启动一个 Activity 似乎对您有用)
  2. 您使用 setExactAnd...setAlarmClocksetAlarmClock 也会在新的“打瞌睡”模式下触发,请参阅 https://stackoverflow.com/a/47049705/1587329 .

另一种方法是重新思考为什么以及您是否真的需要这个......或者 JobScheduler 是否无法更轻松地满足您的目的。

关于android - PendingIntent 与 IntentService 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50151374/

相关文章:

java - 如何在android中制作iphone风格的幻灯片动画?

android - proguard 防止逆向工程的安全性如何?

android - 长时间运行的后台进程

android - Intent.putExtras 不一致

java - 即使按下停止按钮也无法停止警报响起

android - 未指定网络安全配置,使用平台默认值 - Android 日志

java - 创建一个信任库以仅验证由 JAVA 中的自定义 CA 签名的证书

android - 我无法在 Android 中取消 Alarms/PendingIntents

android - 从通知打开应用程序

java - 带有 PendingIntent 的 Android 通知的额外 null