Tuesday 9 October 2012

Developing Android Clock Widgets

I recently created a tutorial series for Mobiletuts+ on creating an Android clock widget. It was the first time I had attempted the task, so I thought I'd share a couple of the things I discovered.

Analog or Digital

First, the process for creating analog and digital clocks is totally different. For an analog clock widget, the process is pretty straightforward, in fact the most time consuming part is probably creating your clock design. The basic tasks in creating a simple analog clock widget are as follows:

  • Create a widget project, setup the properties in the Manifest and XML resource file.
  • Create images for the dial, minute and hour hands for each density.
  • Add an AnalogClock element to your layout file.
  • Extend AppWidgetProvider and receive updates.

For a digital clock widget, more programming is involved. There is a DigitalClock class/ View, but unlike the AnalogClock, the DigitalClock cannot be used within the layout for a widget, only within standard apps. This means that you need to implement the details yourself, for example using a Service or AlarmManager for updating the widget appearance - there are potentially serious performance issues.

XML Layout

The following code outlines including an AnalogClock element within your widget layout file:
<AnalogClock
android:id="@+id/AnalogClockID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:dial="@drawable/your_dial_image"
android:hand_hour="@drawable/your_hour_hand_image"
android:hand_minute="@drawable/your_minute_hand_image"
/>
Just replace the dial, minute and hour hand references with the names of your own drawable image files. The minute and hour hands should be included as though pointing at 12 o'clock, with the hands placed centrally horizontally within the dial image.

Clicks

If you do develop an Android clock widget, you need to decide what will happen on user clicks. Users have now come to expect certain behaviour as standard on clicking clock widgets, such as launching the device alarm clock (although there is as yet no standard way of doing this). Another option is to allow the user to configure the clock, choosing between designs - this is what I did in the tutorial series.

Launcher

Although widgets are of course accessed from the device homescreen, there is invariably the issue of users attempting to launch a widget app from the device menu. To accommodate this, you can add a launcher Activity to your widget app, which contains instructions on how to add the widget.

Conclusion

If you haven't attempted any Android widgets yet, don't be afraid to have a go, they are generally not too tough to implement. For clock widgets, it's easy enough as long as you go for analog, a little trickier for digital.

Related Info


1 comment: