Reputation: 940
I have found numerous sources for monitoring battery levels, but none of them describe how to check it at a fixed time interval. Suppose I want to check the battery every n seconds. What is the most efficient way to do this?
Currently, I create a BroadcastReceiver and register it in my service with a filter. I then use a ScheduledExecutor to "fetch" the information from the battery. If I understand what's going on correctly, the BroadcastReceiver I made receives all broadcasts from the battery rather at a dynamic rate as they come in, rather than the constant rate I want to check it at.
It appears that when I create the BroadcastReceiver, it receives an "initial" message with the current info. Would it be more efficient to create a receiver object every so often, receive this initial message, then destroy it every time I want to check it? Or, is there a different way that I haven't thought about?
Sources that I used for monitoring the battery, in case if anybody is interested:
Upvotes: 4
Views: 1517
Reputation: 1007296
Suppose I want to check the battery every n seconds. What is the most efficient way to do this?
Unless n
is measured in hundreds or thousands of seconds, you may well be the #1 consumer of battery life. Given your comment, I will assume that you really mean "every n minutes".
Step #1: Set up an AlarmManager
schedule to invoke an IntentService
every n
minutes (preferably not with a _WAKEUP
alarm type).
Step #2: In that IntentService
, call registerReceiver()
with a null
BroadcastReceiver
and an IntentFilter
that is for ACTION_BATTERY_CHANGED
. The return value will be the last Intent
broadcast for this event.
Step #3: Do something with the data.
Upvotes: 2