I am developing an App which gets a maximum temperature from the user. It keeps on monitoring the current temperature of the battery. And once the temperature goes above the maximum temperature got from user, it should notify user.
I designed layouts, wrote logic to store the temperature from the user and i know i can monitor the temperature using EXTRA_TEMPERATURE. However, this app should run in the background. Since I have to monitor the temperature always,logically the service should always run.
On reading forums i understand this will drain battery a lot and mostly can have services running when the screen is on. But, i would like to know if the service can be had in Background without draining battery. Or is there any other way to achieve this?
My app is similar to this : Creating a temperature-sensing Android app that runs in the background after activation
Since I have to monitor the temperature always,logically the service should always run.
Ick.
Or is there any other way to achieve this?
Step #1: Allow the user to choose a polling period (one minute, five minutes, 10 minutes, etc.).
Step #2: Set up an AlarmManager
schedule to get control at the times based on that polling period, routing control to a BroadcastReceiver
.
Step #3: In onReceive()
of the BroadcastReceiver
, get the last-broadcast battery information via registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED))
, pick out EXTRA_TEMPERATURE
, and process it according to your current algorithm. If the work to be done here will exceed a couple of milliseconds, consider delegating that work to an IntentService
, which can do the work on a background thread.
This way, you do not need to keep a process in memory all the time, and the user can choose how aggressively they want to monitor the temperature -- the more aggressive the monitoring, the greater the battery cost (and, ironically, the more the monitoring will increase the battery temperature).