Advertisement

Tutorial – Creating a Custom Analog Clock Widget

Hi all… Note, I am going to assume that there are at least a few people who have wandered off, gotten lost, and somehow ended up here. Hopefully, a few of you meant to be here too…

Yesterday, I was perusing the forums over at www.androidandme.com (as I often do) and one of the members had posted a question related to development. Of course, I hunt these down and pounce whenever I see them. So, on to the question, which I am going to strip down to the scope of this post… How does one write a custom Analog Clock Home Screen Widget for Android.

AnalogClockSo, as I am sure you have already guessed, I have decided to write a tutorial (with code) to explain in detail how to do just that.

Before we continue, I should point out that as I am writing this I am going to assume that you have obtained, installed, and know how to use the software tools for Android Development. For the purpose of this tutorial, these tools are: JDK 1.5 or higher, Android 1.5 SDK, Eclipse 3.4 or higher, and the Android Development Tools Plugin for Eclipse.

Now that that is all out of the way, let’s move on to the tutorial…

First off, we are going to create a new Android Project in Eclipse. For my own code for the tutorial (which can be downloaded here), I will call the Project AnalogClockWidget, I will choose Android 1.5 as the build target (required for Widgets), I will set the Application Name to Analog Clock Widget, the package name to nEx.Software.Tutorials.Widgets.AnalogClock, and create an Activity called Info (this will be explained later).

During the course of this tutorial we will be creating several files that implement various aspects of the widget. These files we will be creating are:

  • Java Source Files
    • Info.java
    • Widget.java
  • Resource Files
    • res/xml/widget.xml
    • res/layout/info.xml
    • res/layout/widget.xml
    • res/drawable/widgetdial.png
    • res/drawable/widgethour.png
    • res/drawable/widgetminute.png

We will also be working with AndroidManifest.xml within the root directory of our project.

Resource Files

The most logical place to start in creating a widget such as this is creating the layout files and the xml file declaring the app-widgetprovider (in our case, res/xml/widget.xml).

res/xml/widget.xml: This file contains the definition of our Analog Clock widget. It is an xml file with only one element: appwidget-provider, which has the following attributes: xmlns:android (standard in Android resource files, defines the android namespace), android:minWidth (defines the minimum width of our Widget, translates to number of cells in the horizontal space), android:minHeight (defines the minimum height of our Widget, translates to number of cells in the vertical space), android:updatePeriodMillis (defines the update frequency, a value of 0 means no updates), android:initialLayout (a pointer to the layout file to display during loading of the widget).

the graphics I am using for this custom version of the Analog Clock will be a nEx.software themed version of the original Analog Clock. As such, I am going to use the same size parameters as the original. That that is, my Clock Dial will be 146ppx by 146 px. Ecah hand will be 14px by 146px.  This size will fit nicely into a 2 cell by 2 cell space on the home screen (in both landscape and portrait modes), just like the original clock. Note that we refer to res/layout/widget.xml here as our android:initialLayout.

Click the link at the beginning of this section to see what our widget definition should look like.

res/layout/info.xml: This file simply provides the layout for an information screen to tell the user about your widget, and provide instructions on how to use it. In our case, we have a very simple widget which requires no configuration, and no special instructions so it will be a very simple layout containing only a LinearLayout and TextView. More complex widgets will usually require more complex information screens.

Click the link at the beginning of this section to see what our info screen should look like.

res/layout/widget.xml: This file provides the layout which we will use for our widget. Again, because this is a simple widget this will be a simple file. In fact, the only elements we will include here are RelativeLayout and AnalogClock. This could also be done without the RelativeLayout, but I usually prefer to have a container in my layout.

Click the link at the beginning of this section to see what our widget should look like.

The remainder of the Resource files listed above are just the graphics we will use for the clock, and need not be specifically mentioned here.

Java Source Files

Info.java: This class extends Activity, and only serves to provide an informational screen to the user. Technically, this is not required for a Widget project, but I recommend it for the following reason:

If you plan to release to the Android Market, it will mitigate those useless and uninformed comments such as “It doesn’t launch.” or “Please remove from the app drawer.” and help you to achieve and retain a better ranking in the Android Market. So, I know you are thinking now “Spill the beans already!” so here it goes… Provide an Info activity which opens from the Android Market when the user presses the Open button, but does not add itself to the app drawer (Launcher). Sounds simple enough, so how do we do it? All you need to do is open the AndroidManifest.xml file,

and replace

android.intent.category.LAUNCHER

with

android.intent.category.INFO.

It’s amazing how a simple change like this can easily amount to a full star or more in your Android Market rankings.

While we are in the AndroidManifest.xml file, we might as well make our other required changes too. Because this is a widget project, we must define our widget in the manifest. To do this, you must define a receiver tag with an intent-filter for android.appwidget.action.APPWIDGET_UPDATE and including a meta-data tag which defines the resource file for the widget.

Click here to see what your AndroidManifest.xml file should now look like.

Widget.java: This is where the magic happens, and is where we will spend the rest of this tutorial. In order to create and use a widget we must extend AppWidgetProvider. Remember, we already added the reference to this class in the AndroidManifest.xml file.

Because this is a very simple widget that relies on nothing but itself (no calls to the web, no background updates, etc…) our Widget class will be very simple. We will only handle the onReceive event that gets called by the AppWidget framework whenever a Widget is Added, Deleted, Updated, etc…

In this onReceive method we will only look watch for the “update” event, so that we can reapply our Widget when appropriate. For some reason, I decided on a blog format that doesn’t not work exceptionally well for including code within a post (layout is not really wide enough). Until I find a better layout for this sort of thing, please click here to view the code sample for our onReceive method.

At this point, we actually have a working Analog Clock Widget, and could compile and use it as is. But that wouldn’t be any fun. What we also want to do is handle when the user clicks on the Clock, and take the user to the Alarm Clock application. to do that, we must create a PendingIntent, and assign it to the click event for the widget. Do do that we will add to the onReceive method three lines. Please click here for the updated code.

At this point, all that is left is to replace the widgetdial.png, widgethour.png, and widgetminute.png in the res/drawable/folder with your own graphics, compile, and install.

You can download my Eclipse project for this widget here.

Regrettably, I somewhat rushed this tutorial, since I had promised to get it out as soon as possible, and I am aware that there are things that could be done better (formatting, maybe more verbose, maybe simpler terminology, possibly different writing style). I intend to update this tutorial in the coming days to be fix some of these issues. Please let me know what I can do better, and offer any suggestions for improvements for this and future tutorials.

72 Responses to “Tutorial – Creating a Custom Analog Clock Widget”

  • morison dony says:

    Very nice information. Thanks for this.

  • dwtaylor99 says:

    I don’t fully understand what’s happening here. I’m an experienced Java programmer, but I don’t understand how the code orients the hand of the clock to tell time.

    I downloaded the Eclipse project and don’t see any code regarding the display of time. I admit that I didn’t actually try to run to code.

    I’d love to have a framework to use to create custom clocks. What am I missing?

  • admin says:

    The built-in AnalogClock widget handles all of that. As long as you are following the standard hands rotating about the center model, you do not have to do anything special. Now, if you wanted to have different clock format, then you would have to handle that differently. I should put up that tutorial as it is much more interesting. Stay tuned.

  • MadAir says:

    I enjoyed this tutorial. I had seen alot of widgets for clocks for the Android and wondered how they were made. This answers this question. Thanks for the tutorial and look forward to your next.

  • Lyndon says:

    Hi

    I’m new to Android but a Java pro.

    I’m trying to get the tutorial working but I get this in the Eclipse console:

    AnalogClockWidget]——————————
    AnalogClockWidget]Android Launch!
    AnalogClockWidget]adb is running normally.
    AnalogClockWidget]No Launcher activity found!
    AnalogClockWidget]The launch will only sync the application package on the device!
    AnalogClockWidget]Performing sync
    AnalogClockWidget]Automatic Target Mode: using existing emulator ’emulator-5554′ running compatible AVD ’em15′
    AnalogClockWidget]Uploading AnalogClockWidget.apk onto device ’emulator-5554′
    AnalogClockWidget]Installing AnalogClockWidget.apk…
    AnalogClockWidget]Success!
    AnalogClockWidget]\AnalogClockWidget\bin\AnalogClockWidget.apk installed on device
    AnalogClockWidget]Done!

    Nothing happens in the emulator ‘phone’…

    I have a ‘Hello Android’ program working so Eclipse and ADT must be sort of ok.

    Any ideas?

    Regards

    Lyndon

  • Diggidy says:

    Great tutorial, very informative thank you. How would you make the clock transparent? That would give it a nice touch.

  • lostwh3re says:

    how would you go about making multiple widgets for one app? I can make one analog clock with one app how can i make multiple ones per application like in the market place

  • Silentmyst says:

    Lyndon: Because this is a widget and not an application you actually have to start the emulator first by running C:\path-to-android-sdk\emulator -avd myAvd in command prompt

    Or whatever your path is to the android SDK then run the widget like you normally would from Eclipse and it will ask which emulator you want to install it on. Pick the one you just ran, add the widget like you normally would and your golden.

    Note if you don’t know your virtual device name type into command prompt
    C:\path-to-android-sdk\android list avd

  • Brandon says:

    Thank you soo much for this tut. but i have one question i took the easy way out and download the project and now i modified it to my liking do you know how to change the platform it runs on? i need it to run on 2.0.1

  • John says:

    If i want to install two widgets with different name, what do i change to have them listed with different name instead of the “custom analog clock” in the widgets list?

    Even if i create 2 projects with different name one overrides the other.

    Thanks

  • admin says:

    A Widget is an Application. In many cases, there is no Launcher activity. The emulator should start up automatically just like any other application. Odd that it would behave differently for you. It is a good thing to know how to start an emulator manually though, so thanks for that at the very least.

  • admin says:

    Lyndon, you’d need to long press the Home screen to bring up the Widgets menu, then select Custom Analog Clock.

  • admin says:

    To make the clock transparent, you would just update the graphics to include transparency. The system will do the rest.

  • admin says:

    The Package Name must be different for each application as that is the identifier for the app.

    You might wish to have com.whatever.clock1 and com.whatever.clock2 as the package names for your two widgets.

  • admin says:

    It should just run on 2.0.1, however you may wish to to the following:
    Right click the Project in Eclipse, choose properties, then under Android, change the Target.
    You’ll want to remember to add additional graphics (in the appropriate folders) for the varying pixel densities.

  • This post is actually the greatest on this worthwhile topic. I concur with your conclusions and will eagerly look forward to your forthcoming updates. Saying thanks will not just be sufficient, for the great lucidity in your writing. I will right away grab your rss feed to stay in the loop of any updates. Great work and good luck in your life!

  • hexskrew says:

    This is awesome! I have just ventured into android development last night (as far as getting eclipe, the adk, etc. setup and the hello world app working :P)

    Dude if you keep writing tutorials and posting, this site will surely be epic! (btw, google – ‘android how to make a clock’ and your the first link!)

  • Raymond says:

    Thanks for the tutorial!

    I was in the same boat as dwtaylor99 where I didn’t understand where the calculations and movement of the hands was happening. I’m very new to Android.

    Would be nice to see another example showing how something more customized is done.

  • todd says:

    How do i get it so i can have 2 or more analog clocks that i make in one apk file? so i can make like a clock pack? do i have to make different .xml files for each clock and make a package for each clock?

  • JewsOnIce says:

    Wow I didn’t know u had tutorials. This could come in handy….

  • Jim says:

    Hi,

    This tutorial is great. I just have one issue, I cannot download your code. There is no link. Can it be sent to me via email? Or can you re-post it? Thank you. Again, really great tutorial.

  • gabea101 says:

    I downloaded your code and created a android project just like you said using 1.5. I drag the file over to the eclipse project. I click on run android project and all I get is the hello world, info black screen. Where is the analog clock???

  • Silvan says:

    Hi there!

    Nice tutorial. ***** Can you plz explane how to put more clock widgets (or clock skins) in one apk and how to add sounds for it (Alarm Clock)? Or can you maybe make one tutorial how to make Analog Clock with date?

    Best regards!

  • Miroslav says:

    Hi!

    Nice tutorial! Can you plz explane what should I do to make clock bigger but to stay centered or top centerd on screen? You use 146px x 146px widgetdial.png. I tryed to put bigger photo but it stay same. What I do wrong?

    Thx!

  • Deepak says:

    Hi,

    Great tutorial!!

    I was planning to include a clock in my app activity (not as a widget). So, can you please help me ? What changes I should do if I have to include a clock in my app activity and also it should work like a normal clock, i.e the time should get updated.

    Thanks!

  • anhhai680 says:

    Thanks for share,I become to android because it’s very useful.

  • Hi,
    Nice beginner tutorial. Would you like to submit similar tutorials for our upcoming mobile blog at http://wedesignapps.com
    Visit http://wedesignapps.com/register to sign up free (wordpress backend) and I will promote you as author and you can start posting articles and link back to your blog, get more exposure to your apps in our showcase or featured gallery and also participate in the community.

  • pero says:

    how can we position(the center should be of) widgethour and widgetminute higher or lower.

  • Anoop says:

    good tutorial….
    can u please tell me how to include minute and in the clock

  • Anoop says:

    ^
    i mean seconds hand

  • Anoop says:

    Great tutorial….

    Please let me know if we can add seconds hand in the widget….

  • Silvan says:

    hallo,

    it seems to me that this code is not working for froyo. if i tap on clock nothing happened. how can i fix that issue?

  • Anoop,
    standard alarm clock widget don’t have second hand. So you can’t add it with this code. You must make your own code or something like clock widget by HTC phones.

  • @ pero,

    you can do that with photoshop. best if you make larger transparent photo (206×206) and than put widget dial photo (146×146) in the middle and than pull it up or down. than save it like widgetdial.png. in xml/widget.xml give those valuses:
    android:minHeight=”206dip” android:minWidth=”206dip”.

    if you like taht your clock is always centered (but you can move it up or down) give those valuses:
    android:minHeight=”206dip” android:minWidth=”319dip”.

    if you like bigger clock (260×260) and would like to have one row of icons, give those values:

    android:minHeight=”235dip” android:minWidth=”319dip”.

  • Yakshath says:

    i am not able to get the output…the emulator is showing blank window…….so please tell me the reason……

  • anon says:

    This code works but force closes if app was opened how do you fix this?

  • John says:

    You. Are. Awesome.

    Thank you.

  • John says:

    By Silvan:
    “it seems to me that this code is not working for froyo. if i tap on clock nothing happened. how can i fix that issue?”

    Did you ever find an answer to this? I have the same issue. Actually, the code above works everywhere, including all of my AVDs, etc. BUT it fails miserably on the DROID 2 (Motorola), and I have been unable to solve that… Anyone? SickSeal Soft? Great work, still love it – just having trouble on the ACTUAL phone! lol

    Thank to anyone with a pointer!

  • george says:

    Hello, i am trying to make a digital clock widget but i was wondering if i get any help to replace the digit numbers with graphics numbers like with the analog clock when we change the handles.
    regards.

  • Kunha says:

    Very nice demo

    i looked every where for a simple click choose save process!

    Thanks you.

  • Arith says:

    Where do I get Widget.java from? How do I implement it? Im suck here, can anybody please help me?

  • Tmmm says:

    Te link to your sample code is not working. Where can I get the code?

  • jason says:

    this is a very nice tutorial, but i have ran into an issue. I get it to install but when i run it, i get a forced closed but the clock runs just fine. i ran a catlog. it said that the runtimeexception:
    unable to instantuate receiver (name) classnotfoundexception

  • admin says:

    @Tmmm Odd, the link is working for me.

    @Arith Download the sample code linked at the bottom of the post, everything you need should be in there.

    @jason How are you running it? There shouldn’t be anything to run, just add it to the home screen as a widget.

Leave a Reply