Activities and services using handlers

2019-08-26 17:13发布

问题:

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