Search code examples
androidandroid-intentandroid-broadcast

android.intent.action.BATTERY_CHANGED only when battery level changes not when registering receiver


I am working on an Android project and I am registering a broadcast receiver for android.intent.action.BATTERY_CHANGED. I only want this to be handled when the level is 100% to indicate that the battery has fully charged.

However, as soon as the broadcast is registered, I receive the intent saying that the battery status has changed.

Is there a way to to stop receiving broadcast when the intent is first registered?


Solution

  • Nope, there's no real knobs on it. You're registered or you're not. What you can do is set a static variable in your receiver that's defaulted to false. In your onReceive, look at that variable. If it's false, set it to true and return (do nothing else). It its true, process the event. It needs to be a static because receivers are not necessarily the same object between calls if launched via the manifest (haven't checked when registered via registerReceiver).