AlarmManager / App Widget / Lockscreen / Text Clock

TextClock Version 2 – Part 6

In the previous article I covered the various solutions that I tried to resolve an issue that had developed within TextClock. The time is actually updating anything up to a minute later than it should be, and the problem was caused by internal changes to AlarmManager which were introduced in KitKat. In this article in this we’ll implement the fix.

widget-smallThe first thing that we need to do to implement our fix is to convert TextClockService to TextClockReceiver. This only really requires us to extend BroadcastReceiver instead of IntentService, change the name of the class itself, and override onReceived(Intent intent) instead of handleIntent(Intent intent). The other thing that we must do is change AlarmManager calls from setRepeating(). There is no direct replacement for this to get an exact repeating alarm, so we must change things slightly. When we set the alarm it will be a one-shot alarm – meaning that it will only fire once. When it fires, we update the widget and then set a new one-shot alarm to go off at the next minute tick over:

Note how we ned to set our alarm in the traditional manner for pre-KitKat devices, but using the new method for KitKat and later.

Next we need to change the Service declaration in our Manifest to our Receiver:

Finally we need to update our TextClockAppWidget to fire an initial update when the widget is initialised. We also need to cancel any outstanding alarms if the last widget instance is removed:

Finally we have out widget updating correctly!

That concludes our revisit of the TextClock widget. I may, of course, re-visit it in the future to add new features. If you have any strong opinions either way of whether I should or should not revisit TextClock again, or have any feature requests (or indeed any other requests for topics that you’d like to see covered on Styling Android), then please let me know.

The source code for this article can be found here, and TextClock is available from Google Play.

© 2014, Mark Allison. All rights reserved.

CC BY-NC-SA 4.0 TextClock Version 2 – Part 6 by Styling Android is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. Permissions beyond the scope of this license may be available at http://blog.stylingandroid.com/license-information.

Leave a Reply

Your email address will not be published. Required fields are marked *