2

I'm just wondering if is there any possibility to obtain battery status in broadcast receiver class that fires on ACTION_POWER_CONNECTED? Documentation suggest not, but it is always worth to ask :)

Cheers Ray

Ray
  • 582
  • 1
  • 7
  • 15

1 Answers1

1

Call registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)). The Intent that is returned is the last-broadcast ACTION_BATTERY_CHANGED broadcast, which has your battery status in its extras (see BatteryManager for the keys).

If you determine that you are calling it too soon, that ACTION_POWER_CONNECTED is invoked before ACTION_BATTERY_CHANGED gets updated, perhaps use AlarmManager to schedule yourself to wake up again in a few seconds, and check again then.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Thank you for answer, I tried this already but I got an error message that I cannot register broadcast from other broadcastReceiver. I found in reference that broadcastReceiver may register other receiver only when the former is not declared in manifest file. This forces me to rethink the program... Thanks anyway! – Ray Nov 06 '11 at 18:45
  • @Ray: Sorry, call `context.getApplicationContext().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED))`, where `context` is the Context that was passed into `onReceive()`. For more: http://commonsware.com/blog/2010/09/12/real-use-getapplicationcontext.html – CommonsWare Nov 06 '11 at 21:53
  • Why is it when you register this receiver that you get 8-10 notifications of battery changed? – JPM Dec 12 '12 at 23:02