机器人:运行使用AlarmManager后台任务机器人、后台、任务、AlarmManager

2023-09-12 21:39:39 作者:此id已被河蟹

我在写一个应用程序需要定期检查服务器是否有新邮件,并通知用户。我已经看到了使用一些例子AlarmManager创出BroadcastReciever这似乎是正确的事情,但我似乎无法得到它的工作。

I am writing an app which needs to periodically check the server for new messages and notify the user. I have seen some examples using AlarmManager to hit a BroadcastReciever which seems like the right thing to do, but i cant seem to get it to work.

谁能告诉我一步一步教程这样的事情(重复报警,触发某种背景code触发一个通知)?

Can anyone show me a step by step tutorial for this sort of thing (repeating alarm which triggers some kind of background code that fires a Notification)?

TIA

推荐答案

下面是完整的例子:http://android-in-practice.google$c$c.com/svn/trunk/ch02/DealDroidWithService/

本例中使用了似乎运作良好的模式,和一个我发现,就是用引导接收器设置的 AlarmManager 的(当然还要检查开始从轮询你的主要的活动的太多,当你的应用程序的安装和系统没有启动的情况下),并有 AlarmManager 的发送的意图的另一接收器:http://android-in-practice.google$c$c.com/svn/trunk/ch02/DealDroidWithService/src/com/manning/aip/dealdroid/DealBootReceiver.java

The pattern this example uses, and one that I've found that seems to work well, is to use a boot receiver to setup the AlarmManager (and of course also check to start the polling from your main Activity too, for the case when your app is installed and the system is not booted) and have the AlarmManager send an Intent for another receiver: http://android-in-practice.googlecode.com/svn/trunk/ch02/DealDroidWithService/src/com/manning/aip/dealdroid/DealBootReceiver.java

再从 AlarmReceiver 的启动的 IntentService 的: http://android-in-practice.google$c$c.com/svn/trunk/ch02/DealDroidWithService/src/com/manning/aip/dealdroid/DealAlarmReceiver.java

从你的 IntentService 的然后让你的网络调用来轮询数据,或任何你需要做的。 IntentService 的会自动将您在后台线程的工作,这是非常方便的: http://android-in-practice.google$c$c.com/svn/trunk/ch02/DealDroidWithService/src/com/manning/aip/dealdroid/DealService.java

From your IntentService then make your network call to poll for data, or whatever you need to do. IntentService automatically puts your work in a background thread, it's very handy: http://android-in-practice.googlecode.com/svn/trunk/ch02/DealDroidWithService/src/com/manning/aip/dealdroid/DealService.java

检查文档这些类也有很多到那里。

Check the docs for these classes too, a lot of into in there.

这个例子需要说明的是,它的没有的处理之后锁定间隙(优秀CommonsWare code呢,如果你需要的话),但它可能给你一些更多的想法有关如何解决潜在的东西。使用AlarmManager和服务调查

The caveat with this example is that it does not deal with the wake lock gap (the excellent CommonsWare code does that if you need it), but it may give you some more ideas about how to potentially address the "poll using AlarmManager and Service" stuff.