Good evening, I wrote a tutorial on how to write a widget to display the battery level on t开发者_JAVA技巧he Android but I've found that my widget doesn't always keep in sync with what's shown in the "About Phone>Status" screen. I've installed a closed source widget to see if it was always in sync with the "official" value and it does.
You can access the full code here https://github.com/hmrocha/Batteroid and the tutorial here http://androidappdev.org/2011/05/29/androidappdev-batteroid/
For the purpose of my question I'll post here my onReceive method so that you may see if the problem is there:
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
Integer level = intent.getIntExtra("level", -1);
this.views.setTextViewText(R.id.battery_level, level.toString());
ComponentName cn =
new ComponentName(context, BatteroidAppWidgetProvider.class);
AppWidgetManager.getInstance(context).updateAppWidget(cn, this.views);
}
super.onReceive(context, intent);
}
I really don't know why it stops getting the ACTION_BATTERY_CHANGED intent after some time. The value where it stops is completely random so it's a nightmare to debug.
Thanks for the help in advance.
That ACTION_BATTERY_CHANGED receivers only receive notifications when they are running is unexpectedly documented in Intent.ACTION_POWER_DISCONNECTED, but not mentioned in the ACTION_BATTERY_CHANGED section. So, if your receiver isn't attached to a running process, it won't receive the broadcasts. If you don't want to have a more-or-less permanently running process, then you can update on a schedule, as many App Widgets do, but of course this causes potential and likely delays between battery level changes and display updates, as you're already seeing.
There are open source battery widget apps, including GeekYouUp's Battery Widget and Sergej Shafarenka's Quick Battery.
I posted corrections and explanations for GeekYouUp's Battery Widget at http://programmerbruce.blogspot.com/2011/05/fixing-geekyouups-battery-widget.html.
精彩评论