android - 即使应用程序关闭也能使用警报管理器?

标签 android alarmmanager

我正在使用一个 Alarm Manager 来更新一个带有 Service 的小部件。我有两个不同的问题。

第一个问题:我是按照 Alarm Manager 的 Intent 调用该服务的。像这样:

alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, MyService.class);
pi = PendingIntent.getService(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);

context.startService(new Intent(context, MyService.class));

Long repeat = Long.parseLong(prefs.getString("update_preference", "600"));
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis(), 1000*repeat, pi);

错了吗?

它看起来和工作正常。但是当我查看工作服务时,我在列表中看不到我的服务名称。也许它不是作为单一/独立 服务运行的。刚看到应用程序名称(不是作为服务)。我不确定如何分开或它是否重要?

另一个问题:长时间以来,控制小部件更新的正在运行的应用程序以某种方式关闭(手动或由任务 killer )。当然 Alarm Manager 会停止,widget 的功能也会停止。例如按钮点击。

但是,Twitter 解决了这个问题。当小部件处于 Activity 状态时,如果我关闭控制小部件的主应用程序 (Twitter),而不是单击小部件,小部件会以某种方式触发应用程序并再次启动。所以按钮可以正常工作。这怎么可能?

如有任何帮助,我们将不胜感激。

最佳答案

您不需要执行 context.startservice 来说明未决 Intent 的用途,如果您希望服务在第一次运行时立即运行,只需将其设置为在当前时间运行,然后设置从当前时间开始的间隔。

当您不需要 setRepeating 时,您还设置了 2 种不同类型的重复,而 setInexact 不是,并且可以在操作系统获取时进行调整因此被解雇了。你想要其中之一,而不是两者。

此外,这些间隔时间非常短,会显着耗尽电池电量。

应该就是这个

alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, MyService.class);
pi = PendingIntent.getService(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);

Long repeat = Long.parseLong(prefs.getString("update_preference", "600"));
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,
                      Calendar.getInstance().getTimeInMillis(), 1000*repeat, pi);

关于android - 即使应用程序关闭也能使用警报管理器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10505757/

相关文章:

android - 如何使用 AlarmManager 有效跟踪警报计数

android - android中的警报管理器

java - 操作栏背景大小,Android

android - Kotlin - 将数据从 Activity 发送回 fragment

java - 查找 gradle 构建项目的问题

java - setRepeating() 没有正确重复

java - Android 警报立即触发

Android Studio - 模拟器不加载我的应用程序

android - 无法在 Android 应用程序上使用新图像更改旧启动图像

android - AppWidget 警报管理器未更新