我的应用程序需要执行一个特定的任务每隔一小时。这不要紧,如果应用程序是乳宁,暂停,甚至关闭。
My app needs to execute a specific task every hour. It does not matter if app is runing, suspended, or even closed.
当应用程序正在运行或暂停,我可以只安排一个AlarmManager的BroadcastReceiver做到这一点。但是,当应用程序被关闭,我必须调用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型的,长triggerAtTime,间隔长,PendingIntent操作)
这一点。将类型设置为 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这个方法。您不必担心泄露意图。
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.
不注册在code接收器这一点。只需添加一个<意向滤光器>
标签来为您的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>