Android:如何安排即使我的应用程序关闭也会调用的alarmmanager广播事件? [英] Android: how to schedule an alarmmanager broadcast event that will be called even if my application is closed?
问题描述
我的应用需要每小时执行一次特定任务.应用程序是否正在运行、暂停甚至关闭都没有关系.
My app needs to execute a specific task every hour. It does not matter if app is runing, suspended, or even closed.
当应用程序正在运行或暂停时,我可以通过调度一个 AlarmManager 广播接收器来实现.但是当应用程序关闭时,我必须调用unregisterReceiver"才能不泄漏意图,并且应用程序永远不会被唤醒(或其他东西)来处理任务.
When app is running or suspended, I can do it by just scheduling an AlarmManager broadcastreceiver. But when the application is closed, I have to call "unregisterReceiver" to not leak an intent, and app will never be wake up (or something) to process the task.
那么,问题是:如何调度一个不需要注销的alarmmanager任务,这样即使我的应用程序关闭也会被调用?
推荐答案
为此使用AlarmManager.setRepeating(int type, long triggerAtTime, long interval, PendingIntent operation)
.将类型设置为 AlarmManager.RTC_WAKEUP
以确保设备在睡眠时被唤醒(如果这是您的要求).
Use AlarmManager.setRepeating(int type, long triggerAtTime, long interval, PendingIntent operation)
for this. Set the type to AlarmManager.RTC_WAKEUP
to make sure that the device is woken up if it is sleeping (if that is your requirement).
像这样:
Intent intent = new Intent("com.foo.android.MY_TIMER");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
long now = System.currentTimeMillis();
long interval = 60 * 60 * 1000; // 1 hour
manager.setRepeating(AlarmManager.RTC_WAKEUP, now + interval, interval,
pendingIntent); // Schedule timer for one hour from now and every hour after that
您将 PendingIntent 传递给此方法.您无需担心泄露 Intent.
You pass a PendingIntent to this method. You don't need to worry about leaking Intents.
当你不再需要它时,记得通过调用 AlarmManager.cancel()
来关闭它.
Remember to turn the alarm off by calling AlarmManager.cancel()
when you don't need it anymore.
不要为此在代码中注册接收器.只需将
标记添加到您的 BroadcastReceiver 的清单条目中,如下所示:
Don't register a Receiver in code for this. Just add an <intent-filter>
tag to the manifest entry for your BroadcastReceiver, like this:
<receiver android:name=".MyReceiver">
<intent-filter>
<action
android:name="com.foo.android.MY_TIMER"/>
</intent-filter>
</receiver>
这篇关于Android:如何安排即使我的应用程序关闭也会调用的alarmmanager广播事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!