Activities and services using handlers

為{幸葍}努か 提交于 2019-12-25 06:53:48

问题


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


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/5817782/activities-and-services-using-handlers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!