Search code examples
androidbroadcastreceiverandroid-servicealarmmanager

Knowing BatteryManager.Battery_Status_Full after receiving ACTION_BATTERY_CHANGED thru BroadcastReceiver


I am working on a app wherein, I need to update the time in db when either Battery_Status_Full happens (battery is charged 100%) / charging is disconnected, whichever occurs first.

I am able to get the Battery disconnect event and update the db based on that event, but while the device is still charging and reaches 100% charge, when inside the Service - onCreate I have registered the broadcastReceiver with IntentFilter(Intent.ACTION_BATTERY_CHANGED) and trying to fire a repetitive event after say every 5 mins to check if 100% battery charging is completed, I seem to never receive the 100% event and hence always the disconnect db update happens and not the 100% charging update. Also, with my AlarmManager, the service to check for 100% battery charging is fired only once and not repetitively.

Please guide. I am almost done with my app, but this small bug is making me go crazy. Thanks Omkar Ghaisas

---- More Details ---- My app architecture is as below,

  1. BroadcastReceiver (registered for ACTION_POWER_CONNECTED AND ACTION_POWERDISCONNECTED). In each case, it starts a separate Service to handle DB transactions. For POwer connected it sets the Intent with extra information called ADD and for disconnected, it sets it with Update

  2. When service is started, in its onCreate, it registers a receiver by passing in null broadcastreceiver for IntentFilter ACTION_BATTERY_CHANGED and within onStartCommand, for Add flag in intent, a new entry is saved in db. In case of update flag - only if earlier update db entry is not made, then I go ahead and update the db

  3. I have an AlarmManager with setRepeating below the above Add/Update logic (If-Else) which starts another service by getService(serviceclass.class)

  4. I am expecting that within the new service, when I keep checking if battry level has reached 100% I update the db there itself.

  5. If the battery never reaches 100% and the Battery_Dicsonnected is fired, then inside the Update block above, the db will anyway get updated, with whatever battery level is at that time.

Doubts / concerns -

  • But the problem is that, the new service getting invoked from alarmmanager is started / invoked only once.
  • Where do I exactly place this alarm manager in 1st service ?
  • Is the 2nd service created for constantly keep checking the battery level reaching 100% needed at all ?

Pls guide. I can very well post the code, if that's needed. Thanks Omkar


Solution

  • I figured this out finally. My positioning of alarmmanager was wrong. I fixed that and also removed the unnecessary 2nd service just to check if 100% battery level was reached. Finally everythings' working as expected. :-) wow I feel so overjoyous with my first android app working as expected. Thanks for all the help though. Omkar