ACTION_BATTERY_CHANGED firing like crazy

女生的网名这么多〃 提交于 2019-11-27 13:43:58

My code looks like this:

You cannot register a BroadcastReceiver from another BroadcastReceiver and get reliable results. Android will terminate your process, because it doesn't think anything is running. The only way to listen for ACTION_BATTERY_CHANGED will be to register that receiver from an activity or a service.

Isn't this only supposed to be broadcast for each percent decrease?

Where do you see that documented? AFAIK, ACTION_BATTERY_CHANGED will be broadcast whenever the hardware feels like it. Also, bear in mind that other data changes within that Intent, such as temperature.

If you want to implement this app widget, do not register for ACTION_BATTERY_CHANGED the way you are. Instead:

  • Allow the user to choose a polling period via a SharedPreference (e.g., once a minute, once every 15 mintues)
  • Use AlarmManager to give you control on that polling period via a getBroadcast() PendingIntent
  • In that BroadcastReceiver, call registerReceiver() for ACTION_BATTERY_CHANGED but with a null BroadcastReceiver, as this will return to you the last Intent that was broadcast for that action (note: you will still need to use getApplicationContext() for this)
  • Use AppWidgetManager to update your app widget instances with the battery level pulled out of the Intent you retrieved in the preceding step (note: if you are setting them all to be the same, you do not need to iterate over the IDs -- use the updateAppWidget() that takes a ComponentName as a parameter)

This has several advantages:

  1. You do not care how often ACTION_BATTERY_CHANGED is broadcast
  2. The user gets to control how much battery you consume by doing these checks (should be negligible if you keep the polling period to a minute or more)
  3. Your process can be safely terminated in between polls, thereby making it less likely that users will attack you with task killers and semi-permanently mess up your app

Well, your onUpdate is registering its own class as receiver for the batteryinfo intent. This intent is then immediately triggered for the first info. Your onReceive is calling your onUpdate again. We call this a loop. Hence the 100 logs a second ...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!