1

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?

Kara
  • 6,115
  • 16
  • 50
  • 57
psv
  • 3,147
  • 5
  • 32
  • 67

1 Answers1

1

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.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • yes, but the app needs to be started if I register an AlarmManager right ? According to me this code will probably not work if the app is closed : `AlarmManager alarm_manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); alarm_manager.setRepeating(AlarmManager.RTC_WAKEUP, date.getTimeInMillis(), AlarmManager.INTERVAL_DAY , pending_intent);` – psv Aug 14 '13 at 16:00
  • @user2683000: "but the app needs to be started if I register an AlarmManager right" -- you need to get control once to set up your alarms, such as on the first run of your app. You need to get control again on a reboot, as a reboot wipes out all scheduled alarms. Otherwise, `AlarmManager` is *specifically designed* to trigger your code *without* you having a currently-running process at the time. – CommonsWare Aug 14 '13 at 16:08
  • Ok thanks for your answer, I understand now. AlarmManager works well ! – psv Aug 16 '13 at 16:09