Search code examples
androidbroadcastreceiver

Android access battery stats or monitoring battery level through manifest


I want to detect battery change at every percentage. I tried to create a service with

context.registerReceiver(this.myBatteryReceiver,new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

but when the application is closed the service is killed.

I tried to register my broadcast receiver in the manifest with <action android:name="android.intent.action.BATTERY_CHANGED" /> but the documentation says:

You can not receive this through components declared in manifests, only by explicitly registering for it with Context.registerReceiver().

What can I do to monitor the battery level even if the app is closed?

I have seen the permission <uses-permission android:name="android.permission.BATTERY_STATS" />. Can I use it? And if yes, how?


Solution

  • What can I do to monitor the battery level even if the app is closed ?

    Use AlarmManager to check for the battery level periodically. You can call registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); to retrieve the last-broadcast ACTION_BATTERY_CHANGED Intent. Allow the user to control the polling period (e.g., every minute, every 5 minutes), and probably do not use a _WAKEUP alarm, so you will only check the battery level when the device is otherwise in use.