I want to monitor Android battery level, even when it is changed by one percentage. The following two conditions should be satisfied:
1- Because of efficiency I do not want to check the battery level by Polling or Periodically (not using alarm manager, Handler or anything else which leads to polling)
2- On the other hand, I need to receive changes in the battery level even if my application is not in the foreground or if it is killed.
Currently I am using this code:
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
context.registerReceiver(new MyBatteryReceiver(), ifilter);
It works nice until the context (or my activity) is alive, i.e. MyBatteryReceiver receives changes in the battery level.
Others suggest to use null with the registerReceiver:
context.registerReceiver(null, ifilter);
This solution means that I should check the battery level periodically.
I have checked many posts including this one:
Android access battery stats or monitoring battery level through manifest
but none of them answered this question: How to monitor android battery level WITHOUT polling? Of course when the level is too low or too high we can use the following broadcasts:
<action android:name="android.intent.action.ACTION_BATTERY_LOW"/>
<action android:name="android.intent.action.ACTION_BATTERY_OKAY"/>
Unfortunately it is not possible to use a similar broadcast for changes in the battery level:
<action android:name="android.intent.action.BATTERY_CHANGED" />