Previously, under desktop environment, to implement a stock price alert system, here is what I do.
- Spawn a infinity running
Thread. - The thread will perform stock price query from stock server.
- The thread will perform all the necessary alerting actions based on retrieved stock price.
- The thread sleeps for N period. (N can be let’s say 30 minutes)
- Go back to 2.
When comes to mobile environment, power efficiency usage is a major consideration. The stock alert mechanism should keep running, even when I “close” the application using back button.
There are 2 ways out from my mind.
Use Service
- Spawn a infinity running
Service. - The service will perform stock price query from stock server.
- The service will perform all the necessary alerting actions based on retrieved stock price.
- The service sleeps for N period. (N can be let’s say 30 minutes)
- Go back to 2.
Use AlarmManager
- Install a
BroadcastReceiverinAlarmManager. - BroadcastReceiver’s
onReceivewill be triggered in next N period. - When BroadcastReceiver is being triggered, perform stock price query from stock server.
- The BroadcastReceiver will perform all the necessary alerting actions based on retrieved stock price.
- Before returning from
onReceive, install anotherBroadcastReceiverinAlarmManagerfor next N period.
I was wondering, which way is better? Is there any better ways other than the 2 ways? It seems to me AlarmManager is better, as we do not require to sleep for a long period, which seems sort of wasting resource?
Use
AlarmManagerto trigger aBroadcastReceiverthen have theBroadcastReceiverstart anIntentService.A
BroadcastReceivershouldn’t do any long-running tasks but it can start aServiceto do work. AnIntentService(which extendsService) will do work on a worker thread and then self-terminate.See IntentService
And Extending the IntentService class
In other words you can combine both ways that you are considering but without a continually running
Service.