使用处理程序的活动和服务
你好 我正在尝试在应用程序中使用多个服务,我希望在从其中一个服务获取更改的值后一段时间后重新运行这些服务。 请指导我使用处理程序/计时器/广播接收器来实现这一点。
谢谢
Hi
I am trying to use several services in an application, i wish to re-run the services after a certain period of time after fetching the changed values from one of the services.
Pls guide me on implementing this using handlers/timers/broadcast receivers.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该使用发送挂起意图的 AlarmManager。您可以使用多个意图和广播接收器。在广播接收器中您可以启动服务。这样,您可以根据需要在不同时间或一起启动多个服务。
您可以使用 Alarmmanager 发送重复的警报,或者您可以在其中一项服务中使用它并为您的待处理意图设置新时间。
不要使用定时器!
这样做的好处是,当 Activity 不活动时,这一切都可以工作。
您可以绑定到服务,如示例中所示,但如果您想将数据从服务传递到活动,您可以只使用应用程序对象或单例。另外,我会使用 IntentService,它会自动完成主线程的工作。如果你想在不同的线程上做一些与 Activity 更紧密交互的事情,我会使用 AsyncTask 或线程。
You should use an AlarmManager that sends pending intents. You can use multiple intents and broadcast recievers. In the broadcast recievers you can start a service. This way you can start multiple services at different times or together if you want.
You can use the Alarmmanager to send repeated alarms, or you could use it in one of the services and set a new time for your pending intent.
Do not use a timer!
The benefit of doing it this way is that this all works when the Activity is not active.
You can bind to a service as shown in the example, but if you want to pass data from a service to an activity you can just use the application object, or a singleton. Also I would use an IntentService, which automatically does its work of the main thread. If you want to do something on a different thread that should more closely interact with the Activity I would use an AsyncTask or a Thread.
下一页将向您详细介绍broadcastReceiver类和Service在启动时的工作方式。
http://www.androidenea.com/2009/ 09/starting-android-service-after-boot.html
它还实现了计时器功能...但请注意,该方法中的计时器非常快,并使您的模拟器无响应...或缓慢。
对于消息传递部分,请参考此线程。此线程中给出的程序非常酷。程序员的荣誉...
示例:使用消息传递在 Activity 和 Service 之间进行通信
——拉杰什
The following page describes to you in detail the working on a broadcastReceiver class and a Service at start up.
http://www.androidenea.com/2009/09/starting-android-service-after-boot.html
it also implements the Timer functionality... but please be advised that the timer in that method is really fast and makes your emulator unresponsive... or slow.
and for the messaging part please refer this thread.. the Program given in this thread is ultra cool.. kudo to the programmer...
Example: Communication between Activity and Service using Messaging
Regards,
--Rajesh