Click here to Skip to main content
15,441,078 members
Articles / Internet of Things / Wearables
Article
Posted 24 Sep 2015

Stats

20.4K views
164 downloads
4 bookmarked

Creating the watch faces for Android Wear

Rate me:
Please Sign up or sign in to vote.
4.33/5 (7 votes)
24 Sep 2015CPOL20 min read
This article covers how to create new faces for your Android Wear and explains the how-to procedure with a few personal experience notes.

Introduction and Background

I wonder why designers yet aren't into these tech things, where most of the tech stuff already needs someone from designing and fine arts. I have a few friends of mine who have a great taste of designs, contrasts and other relative "fine arts" related stuff but they lack good programming skills, efficiently writing apps for mobile devices. Same applies to me, I although have (better, not great) experience of writing applications that do not conserve much resources but I lack a good taste of design principles. On a desktop, you can create a monster app, but once on a miniature device such as handhelds. You have to worry more about resources, because they don't have much. For example, battery, RAM and other hardware components are the resources that I am talking about. 

While writing a great application for handhelds and other similar mini devices, you have to worry about battery consumption, CPU usage, RAM consumption and other things... Oh and did I mention you also have to make sure that user is paying attention to their surroundings and not wasting their time tapping your "Next", "Next" buttons? These are a few principles one has to follow while writing applications for handhelds and handworns (can I use that name for watches?). That is pretty much self-explanatory, you have to ensure that your application is not consuming too much of CPU, is not executing calculations on a continous threads and also whether it is battery-friendly or not?

In the following article, you will learn how to create an Android Wear application that adds a new Watch Face to the list, plus that it follows the basic programming design patterns to ensure that the resources are not used too much. Where to use CPU and how much to use it, when to store the resources to be used while drawing the Face and where to, also how to draw the content on screen. If you need to add more components to the screen, how to do that. All of that is collected and compiled in one article for you! 

Until the next section, read what I had a chance to hear from OriginalGriff in one of our conversations

I've written a few uController applications which run on batteries, and you have got to be really, really careful. Battery life is significant - and if you add too much processing, you can drastically shorten battery life. With embedded devices, that can mean the customer going to the competition...

The current crop of watches are gawd awful because they are not trying to do that: they are trying to be a a "whole phone" on your wrist - and that uses power, lots of it. Where is the point of a watch that won't last all day unless you are really careful what you do with it? People get annoyed enough with modern phones not holding a charge for long enough...

I am sure you get the point of "being cautious" while developing the applications. :-)

Little bit about Android Wear—Smartwatch of our subject!

Before moving one step forward, I wanted to share a bit about Android Wear itself. Android Wear is a new platform provided by Android under Smartwatch category. Android, the leading smartphone operating system, launched their smartwatch versions quite a time ago. It is gaining a limelight rapidly and soon would gain some marketshare also! 

Little bit about Wear Apps

I have another article already set up for you to get yourself started with Android Wear applications, you can head on to that and read it as it has everything that you would require to understand before creating an actual application for Android Wear. The ABC of Android Wear applications.

In order to actually use an application on a real watch, you would have to connect it to your Android device and then install that application on your device. The device will then push the wear app to the wear device, from where it will run on your device. 

Why this behavior?

In my opinion, I actually like this kind of framework because it leaves most of the job to the handheld. For example, if you want to download the files, get a reply from web service or to store the data on internet. You can do so from the handheld by passing the data to the handheld. 

You would also be able to send requests for network resources to the handheld, handheld in any case will have more battery than the wear device itself. That is why, if you run most of the calculations and store most of the resources on the handheld. It can make your wear application better, in many ways!

Heading off to the studio

In this session I will be using Android Studio to create the wear application and to create the application which has the watch face embedded in itself. The article will only focus on the Watch face part of the application, what it is, how to create it and how to modify it. Plus, how does it look on each device and how to modify the watch based on the device's hardware (square or round). By the end, you will be able to port your ideas to a real Watch! 

First of all, create a new project for Android wear (please read the above article, as it provides you with information about creating a project that can be ported on an Android Wear). Make sure you have selected Empty activities, because I will be guiding you step-by-step to create a new Watch face. So, no templating. Once you have created an empty project, read further. Until this stage you are only required to have IDE open and a project created. 

Creating the Watch Face

If you have ever programmed an Android application then you already are well familiar with Android Services. Android Services are components that run in background to execute a task. They can start and stop, since they have no UI, they should stop once their work is finished. For example, you can play a music file in background using a service and once file has finished playing the service must stop itself (unless on a repeat). Same way, an Android Wear's Watch Face is a service component. It executes in background and keeps drawing a Face on your watch. In this section, I will walk you though many things about a Watch Face including the "What" and "How"s of Watch Face. 

What is a Watch Face

Putting it simple for you, Watch Face is a service that runs in the background and provides you with a facility to draw graphics in the canvas. The graphics are used to create different faces, write the text, build animations and perform other activities that a developer might want to in their graphical application for Watch. However there are a few things that Watch cannot do, or restrains the developer from doing. They are specially designed for system features only. For example while interaction with Watch Face is allowed, but only single tap is provided. Pinch, drag and other features like a handheld has are not provided in Watch Face. 

Android Developers have a great documentation resource in this case and they also provide you with visual feedback and design approaches to be applied to your watches. In this guide you will be taught a few basics about these principles and how to make most out of them in your applications. 

Now, if the purpose of a Watch Face is clear to you I think we should continue to next step and create something for this guide. Throughout the process I will explain every bit that I can so that you can understand the procedure of building the application yourself later when you want to. 

Getting started—Empty project

First of all create a new project, make sure it is empty. A Watch Face basically is a "draw canvas" service. So, in Android APIs there is a service CanvasWatchFaceService and CanvasWatchFaceService.Engine which you need to extend in your application create a Watch Face. The Engine class allows you to actually draw the Watch Face, the methods provided by this class are: 

  1. onCreateEngine
    This function is used to get an instance of Engine object. Which can be then used later for different purposes, timers and drawing etc. 
  2. invalidate
    This function is similar to View.invalidate function. It would prompt the system to re-draw your Watch Face. 
  3. onDraw
    This function is the one we are interested in. It allows us to
    • Draw the objects on canvas. 
    • Provides us with the bounds of the device, to use while drawing over the canvas.
    • Canvas parameter can be used while drawing shapes.
    • Like other APIs, Android Canvas object also provides us with methods to draw shapes, such as
      • Circles
      • Paths
      • Arcs
      • Bitmaps
        They are simply graphics, drawable in Android language. I will show you a code snippet to convert your drawables to Bitmaps, keep reading.
      • Text
    • Perform other Canvas based functions, provided under Android API.
  4. A few more functions that I won't talk about until I have explained the service itself. 

That was simply an overview of the service, next I will show you how to implement it. 

Note: For those who are using Eclipse, please download and install the support libraries and plugins before continuing. They are required, on Android Studio they are already installed once you configure your IDE.

Create a new service, implement the base services for creating a Watch Face. The services would then have the interfaces (functions I mean) for you to perform functions on the device and to determine when an event was occured. Overriding those methods would allow you to perform you own actions. 

I have created the following Java class that would act as the service for our Watch Face. 

Java
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.wearable.watchface.CanvasWatchFaceService;
import android.view.SurfaceHolder;

/**
 * Created by AfzaalAhmad on 09/22/2015.
 */

public class CodeProjectWearFaceService extends CanvasWatchFaceService {
    @Override
    public Engine onCreateEngine() {
        return new Engine();
    }

    private class Engine extends CanvasWatchFaceService.Engine {
        @Override
        public void onCreate(SurfaceHolder holder) {
            super.onCreate(holder);
        }

        @Override
        public void onPropertiesChanged(Bundle properties) {
            super.onPropertiesChanged(properties);
        }

        @Override
        public void onTimeTick() {
            super.onTimeTick();
        }

        @Override
        public void onAmbientModeChanged(boolean inAmbientMode) {
            super.onAmbientModeChanged(inAmbientMode);
        }

        @Override
        public void onDraw(Canvas canvas, Rect bounds) {

        }

        @Override
        public void onVisibilityChanged(boolean visible) {
            super.onVisibilityChanged(visible);
        }
    }
}

The class has the implementation of a service, it is almost ready. We need to provide the meta-data that Wear companion app and the device will use to determine the resources of our Watch Face. In the manifest, you need to register the activity as a service, Android will look into the manifest for any of such processes, so, edit the manifest and add the following service element. 

<service
     android:name=".CodeProjectWearFace"
     android:label="@string/my_digital_name"
     android:permission="android.permission.BIND_WALLPAPER" >
     <meta-data
         android:name="android.service.wallpaper"
         android:resource="@xml/watch_face" />
     <meta-data
         android:name="com.google.android.wearable.watchface.preview"
         android:resource="@drawable/preview_digital" />
     <meta-data
         android:name="com.google.android.wearable.watchface.preview_circular"
         android:resource="@drawable/preview_digital_circular" />

     <intent-filter>
         <action android:name="android.service.wallpaper.WallpaperService" />

         <category android:name="com.google.android.wearable.watchface.category.WATCH_FACE" />
     </intent-filter>
</service>

This would now register your service to be found. Although it is pretty much clear, but let me explain a few of these things here. Now, before we dissect this. I will talk about one more element, wallpaper element. Android Wear Face is drawn on a wallpaper element. You can create a new wallpaper simply. Create a new file under XML folder and name it what you want (in above case, it is watch_face). The code is just 2 lines code, 

XML
<?xml version="1.0" encoding="UTF-8"?>
<wallpaper xmlns:android="http://schemas.android.com/apk/res/android" />

Now I will discuss some more about the service definition. 

  1. android:name
    This attribute specifies the code file, Android uses the code file with this name and runs the code in it. You would then need to override and implement the functions required in that code file. We already did.
  2. android:label
  3. This attribute is used to name the Watch Face in the list. You can use any name, I used "CodeProject Wear Face", a literal string.
  4. meta-data
    These elements specify the meta-data for your service, Watch Face service specifically. Android Wear app or Wear device would use the data specified here and would show the data for your Watch Face. 
    • android.service.wallpaper
      This would specify the wallpaper element, I have described this above and the method to create it. You would need to create it, because these are required.
    • com.google...watchface.preview
      This is the default preview for your Watch Face in a rectangular Wear device. 
    • com.google...watchface.preview_circular
      This is the default preview for your Watch Face in a circular Wear device.
  5. intent-filter
    The intents that this application shows interest in. They are self-explanatory. :-) 

Once that has been done, we can now consider writing the code to actually draw something on the watch. Our Watch Face has been registered in Android app and would now execute the code in the service to perform actions, such as handling the events, drawing on canvas and hiding or showing the data. 

Live preview example

I wanted to show you how our application looks right now, so I think displaying CodeProject on the device would suffice. So I altered the code in the onDraw function and wrote the following code in it, 

Java
@Override
public void onDraw(Canvas canvas, Rect bounds) {
    final Typeface typeface = Typeface.DEFAULT;
    Paint paint = new Paint() 
                  {{ 
                       setTextSize(40); 
                       setARGB(255, 255, 255, 255); 
                       setTypeface(typeface); 
                  }};
    canvas.drawText("CodeProject", 50, 100, paint);
}

The code is easy and a very compact one, does one thing, "Display CodeProject on the watch!" It does, have a look at the following image. It has printed CodeProject using the indices (50, 100) and the paint object that we have passed to it. The paint object would have the graphics details that we want, for example

  1. The size of text that we want. 
  2. Color of the text.
  3. Typeface to use while drawing the text (font-family?)

The function is drawText. There are some other functions also available, such as drawBitmap and drawArc etc. I won't talk about most of them, but drawBitmap will be used here, soon. 

Image 1
Figure 1: (Square) Android Wear showing CodeProject text rendered on it along with the status icons in the top left corner.

Adding some features to it—Intermediate level skill

So far I would expect that you are now aware of canvas, Wear service, CanvasWatchFaceService and the functions it provides us with. I will point out a few of these services and then we will head on to the main section to draw something useful on the canvas! 

Collecting data

Before you create something, you should ask yourself. "What difference does it make?" What more data does it provide your users, what things does it consider, is it even worthy to upload the application for users? These questions would give you an idea of "What" does the application do. 

Although Wear does not have much features as a handheld would have, but you can however use your application to:

  1. Show the date and time.
    I would personally recommend that you use Calendar object, but using Time would allow you to work with more features, I somehow still recommend using Calendar instance to get the date and time. 
  2. Show addition information.
    This is the interesting part, because this is where Wear differs from an ordinary watch. You get to display additional data in the screen also, what ordinary watch doesn't allow. Thus a smartwatch! ;-)
    • Show details of reminders, or a particular one coming in fast.
    • Show weather details.
    • Number of missed calls or messages available to read.
    • Total cards present. 
    • Any other data from any API or data source!

Once you have collected the data, you can display that on the canvas just as you would draw anything else. Write the data, draw an icon and user would be able to see it right on their way. 

By default, Android provides us with many API contracts, such as Calendar. Where you can get the details about reminders, events etc. These contracts allow your application to get data about user's own databases for content. Then using them you can design your own application in a very user-friendly way. That is exactly how other applications get the data for a user. If you are interested, you can always give a look at the WearableCalendarContact class in the support API. 

Creating the members

As already mentioned many times, you must never perform most of the tasks in the Wear itself, it does not have much resources as any other handheld might have. That is why it is not preferred to always keep the CPU or RAM busy. In your onCreateEngine function you can initialize the members, or right in somewhere where you are not going to be most oftenly. 

A very legit reason to do so is that fo reach of the Bitmap that you try to render, each of the Paint object that you want to create needs to be in the RAM and also takes CPU. For example, the Bitmap to be rendered, each pixel needs CPU time to be rendered. Thus the more pixels you would need the more CPU time would be consumed and at the same time more battery would be drained that is why it is always recommended to not create (and/or initialize) the members again and again. Do them once, wisely. 

I am going to think of what am I gonna make? Here is the list of them:

  1. Date-time text
  2. Background color
  3. Image of bob (I hope admins don't mind!)

So, to use them I would need to initialize them earlier, so that when CPU starts to render everything it already has everything and that this process does not gets cycled over and over again. 

Java
// The paints that we are going to use in our application.
Paint textPaint, boldTextPaint, boldTimePaint, normalTimePain, datePaint, backGround;
Bitmap bob;

These are the variables that I am going to use in my application. To provide them with a valid value, I will initialize them in the onCreate function.

Java
// Let us initialize them all here
bob = BitmapFactory.decodeResource(getResources(), R.drawable.CodeProject_Bob_Sticker);
backGround = new Paint() {{ setARGB(255, 255, 140, 0); }};
datePaint = createPaint(false, 25);
textPaint = createPaint(false, 40);
boldTextPaint = createPaint(true, 40);
boldTimePaint = createPaint(true, 40);
normalTimePaint = createPaint(false, 40);

Tip: To convert a drawable resource to a Bitmap object you can use the BitmapFactory and call the decodeResource on it. It would require the resources and the drawable resource to use. 

The function that I am using to create a Paint object is defined as below: 

Java
private Paint createPaint(boolean bold, final int fontSize) {
    Typeface typeface = Typeface.create(Typeface.DEFAULT, Typeface.NORMAL);

    if(bold) {
        typeface.create(Typeface.DEFAULT, Typeface.BOLD);
    }

    return new Paint()
    {{
         setARGB(255, 255, 255, 255);
         setTextSize(fontSize);
    }};
}

This creates a new paint and allows us to use it later for rendering the images. I will try it later, before that I want to explain a few more things. 

Responding to user-interactions

Users can interact with Android Wear, but only single interaction method is provided. Single tap, other taps and gestures are blocked by default because system wants to focus on them itself, why? I have no idea, I do not represent Android. :-)

You are only allowed to use a single tap, to interact with user and then show him a response. You can for sure ignore that, but that is not the case here. You should consider responding to his request. To do so you would need to override onTapCommand function and also you would need to change the style and ensure that your Wear application is being provided with the tap events. First of all, inside the onCreate function change the style of your application and add the request to capture the tap events. 

Java
setWatchFaceStyle(new WatchFaceStyle.Builder(CodeProjectWearFace.this)
    .setAcceptsTapEvents(true)
    .build());

This would now allow our application to handle the tap events, next we need to override the function to actually provide the features and services when user taps on our application. 

Java
@Override
public void onTapCommand(
    @TapType int tapType, int x, int y, long eventTime) {
    switch (tapType) {
        case WatchFaceService.TAP_TYPE_TAP:
            // Handle the tap
            break;

        // There are other cases, not mentioned here. <a href="https://developer.android.com/training/wearables/watch-faces/interacting.html">Read Android guide</a>
        default:
            super.onTapCommand(tapType, x, y, eventTime);
            break;
    }
}

This way you can get the user-interactions. Plus if you give a look at the function's signature you will see that there are two co-ordinate parameters also provided; x and y. These parameters will let us know where did user tap on the screen so that we can trigger a function. Since the canvas is just a drawing board we cannot overlay any application or a hyperlink or any kind of trigger. That is why we would have to determine where our certain feature would be presented when our face is rendered so that we can know user clicked on it! 

Reaching both the device sizes

Since Android Wear comes in both sizes, round and rectangular. It is your duty to make sure that your Watch Face looks alike on both faces and also follows the patterns for both the cases. Most of the UI for rectangular cases would fail on a circular one and the ones built for circular would fail on the rectangular. That is why you have to ensure that you are drawing carefully. 

To actually get the View details you are not provided with any native Wear features or APIs, in this case you would be using Android wallpaper services functions and override them to provide additional view based stuff. I am talking about onApplyWindowInsets(WindowInsets) function of WallpaperService.Engine. The WindowInsets allows you to get whether the device is round or not. So you can create a member determining whether round data must be drawn or square. Depends on the device type. 

Java
@Override
public void onApplyWindowInsets(WindowInsets insets) {
    super.onApplyWindowInsets(insets);
    boolean isRound = insets.isRound();

    if(isRound) {
        // Render the Face in round mode.
    } else {
        // Render the Face in square (or rectangular) mode.
    }
}

I am not going to get in the depth of all of these right now. I am just going to pass them by and share a few code tricks in the advanced level section at the end of the article. 

Managing the Watch Style

Another major concept is to manage the style of the watch, what sort of Face do you want to draw and where do system gets to draw its own data. For example, the hotword "Ok Google" remains on the screen when user turns on the device. You have full priviledge as to where does that gets drawn. How do the peak cards get shown, do system gets to preview the system time or you are going to do that on your own. All of these things are packed in the WatchFaceStyle object of Android API. 

You create a new object and then provide some settings to it. The settings are applied to the renderer (Engine) and the Face is drawn based on those settings. 

Java
WatchFaceStyle style = new WatchFaceStyle.Builder(CodeProjectWatchFaceService.this)
    .setCardPeekMode(WatchFaceStyle.PEEK_MODE_SHORT)
    .setBackgroundVisibility(WatchFaceStyle
                            .BACKGROUND_VISIBILITY_INTERRUPTIVE)
    .setHotwordIndicatorGravity(Gravity.TOP)
    .setAcceptsTapEvents(true)
    .setShowSystemUiTime(false)
    .build();

setWatchFaceStyle(style);

The above styles (the properties) are applied while creating the Watch Face. System would use these to provide you with services, such as event handling mechanism, or to draw the time on your canvas, or like rendering the hotwork. 

Now if all of these points have been understood it is time to continue and do something else. Like to create the Watch Face, because you only need to understand these concepts. 

Creating a simple Watch Face

In this section I will show you the code to actually create a simple Watch Face, the code would be simple enough but afterwards I will try to explain it in parts. :-) 

I managed to create a CodeProject Wear Face for this demonstration. First have a look at what is created, 

Image 2
Figure 2: Displaying the Wear Face on both device sizes. 

That displayed, now I guess I would show the code that is used in the same procedure, not a very much long code a very much short piece of code was used to draw the data.

Note: Just pardon the time conflict, it was because of the times when emulators started. Nothing else.

Java
@Override
public void onDraw(Canvas canvas, Rect bounds) {
    calendar = Calendar.getInstance(); // Re-instance the Calendar, to update the time

    canvas.drawRect(0, 0, bounds.width(), bounds.height(), whiteBackground); // Entire background Canvas
    canvas.drawRect(0, 60, bounds.width(), 240, backGround); // Orange color

    // Day
    canvas.drawText(new SimpleDateFormat("cccc").format(calendar.getTime()), 130, 120, textPaint);

    // String time = String.format("%02d:%02d", mTime.hour, mTime.minute);
    String time = new SimpleDateFormat("hh:mm a").format(calendar.getTime());
    canvas.drawText(time, 130, 170, boldTextPaint);

    String date = new SimpleDateFormat("MMMM dd, yyyy").format(calendar.getTime());
    canvas.drawText(date, 150, 200, darkText);
    canvas.drawBitmap(bob, 0, 40, null);
}

This code would do the trick. As seen in both cases, the Watch Face is drawn without any trouble. But in most of the cases you might want to drop down a few pixels for sake of margins. Like have a look at the "Thursday". In square size it is fair, but in circular shape, it won't give any space while the text is being rendered for "Wednesday", the final "y" may go out of the screen. Always consider making sure that the UI is not having any troubles. 

A general tip would be to first of all determine the screen sizes and then get a fraction of the pixel sizes to render using. Well, Bob looks happy in both the screens. :-) 

Service code

Here is the entire code for the service (The service was generated using a template provided by Android Studio and then modified by myself to create the Watch Face for CodeProject theme, so most of the code is written by Android team themselves)

Java
package com.afzaalahmadzeeshan.wearfaces;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.wearable.watchface.CanvasWatchFaceService;
import android.support.wearable.watchface.WatchFaceService;
import android.support.wearable.watchface.WatchFaceStyle;
import android.text.format.Time;
import android.view.SurfaceHolder;

import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;

/**
 * CodeProject Wear face, which shows Day, time (HH:MM A)
 */
public class CodeProjectWear extends CanvasWatchFaceService {
    private static Paint textPaint, boldTextPaint, backGround, whiteBackground, darkText;
    private static Bitmap bob;
    private static Calendar calendar;
    private static final long INTERACTIVE_UPDATE_RATE_MS = TimeUnit.SECONDS.toMillis(1);
    private static final int MSG_UPDATE_TIME = 0;

    @Override
    public Engine onCreateEngine() {
        return new Engine();
    }

    private class Engine extends CanvasWatchFaceService.Engine {

        final Handler mUpdateTimeHandler = new EngineHandler(this);

        final BroadcastReceiver mTimeZoneReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                calendar = Calendar.getInstance();
            }
        };
        boolean mRegisteredTimeZoneReceiver = false;

        /**
         * Whether the display supports fewer bits for each color in ambient mode. When true, we
         * disable anti-aliasing in ambient mode.
         */
        boolean mLowBitAmbient;

        @Override
        public void onCreate(SurfaceHolder holder) {
            super.onCreate(holder);

            setWatchFaceStyle(new WatchFaceStyle.Builder(CodeProjectWear.this)
                    .setCardPeekMode(WatchFaceStyle.PEEK_MODE_SHORT)
                    .setBackgroundVisibility(WatchFaceStyle.BACKGROUND_VISIBILITY_INTERRUPTIVE)
                    .setShowSystemUiTime(false)
                    .build());

            // Let us initialize them all here
            bob = BitmapFactory.decodeResource(getResources(), R.drawable.codeproject_bob_sticker);
            backGround = new Paint() {{ setARGB(255, 255, 140, 0); }};
            textPaint = createPaint(false, 40);
            boldTextPaint = createPaint(true, 40);
            whiteBackground = createPaint(false, 0);
            darkText = new Paint() {{ setARGB(255, 50, 50, 50); setTextSize(18); }};

            setWatchFaceStyle(new WatchFaceStyle.Builder(CodeProjectWear.this)
                    .setAcceptsTapEvents(true)
                    .build());

            calendar = Calendar.getInstance();
        }

        private Paint createPaint(final boolean bold, final int fontSize) {
            final Typeface typeface = (bold) ? Typeface.DEFAULT_BOLD : Typeface.DEFAULT;

            return new Paint()
            {{
                    setARGB(255, 255, 255, 255);
                    setTextSize(fontSize);
                    setTypeface(typeface);
                    setAntiAlias(true);
            }};
        }

        @Override
        public void onDestroy() {
            mUpdateTimeHandler.removeMessages(MSG_UPDATE_TIME);
            super.onDestroy();
        }

        @Override
        public void onPropertiesChanged(Bundle properties) {
            super.onPropertiesChanged(properties);
            mLowBitAmbient = properties.getBoolean(PROPERTY_LOW_BIT_AMBIENT, false);
        }

        @Override
        public void onTimeTick() {
            super.onTimeTick();
            invalidate();
        }

        @Override
        public void onAmbientModeChanged(boolean inAmbientMode) {
            super.onAmbientModeChanged(inAmbientMode);
            if (inAmbientMode) {
                if (mLowBitAmbient) {
                }
                invalidate();
            }

            // Whether the timer should be running depends on whether we're visible (as well as
            // whether we're in ambient mode), so we may need to start or stop the timer.
            updateTimer();
        }

        @Override
        public void onDraw(Canvas canvas, Rect bounds) {
            calendar = Calendar.getInstance();

            canvas.drawRect(0, 0, bounds.width(), bounds.height(), whiteBackground); // Entire background Canvas
            canvas.drawRect(0, 60, bounds.width(), 240, backGround);

            canvas.drawText(new SimpleDateFormat("cccc").format(calendar.getTime()), 130, 120, textPaint);

            // String time = String.format("%02d:%02d", mTime.hour, mTime.minute);
            String time = new SimpleDateFormat("hh:mm a").format(calendar.getTime());
            canvas.drawText(time, 130, 170, boldTextPaint);

            String date = new SimpleDateFormat("MMMM dd, yyyy").format(calendar.getTime());
            canvas.drawText(date, 150, 200, darkText);
            canvas.drawBitmap(bob, 0, 40, null);
        }

        @Override
        public void onVisibilityChanged(boolean visible) {
            super.onVisibilityChanged(visible);

            if (visible) {
                registerReceiver();
                // Update time zone in case it changed while we weren't visible.
                calendar = Calendar.getInstance();
            } else {
                unregisterReceiver();
            }

            // Whether the timer should be running depends on whether we're visible (as well as
            // whether we're in ambient mode), so we may need to start or stop the timer.
            updateTimer();
        }

        private void registerReceiver() {
            if (mRegisteredTimeZoneReceiver) {
                return;
            }
            mRegisteredTimeZoneReceiver = true;
            IntentFilter filter = new IntentFilter(Intent.ACTION_TIMEZONE_CHANGED);
            CodeProjectWear.this.registerReceiver(mTimeZoneReceiver, filter);
        }

        private void unregisterReceiver() {
            if (!mRegisteredTimeZoneReceiver) {
                return;
            }
            mRegisteredTimeZoneReceiver = false;
            CodeProjectWear.this.unregisterReceiver(mTimeZoneReceiver);
        }

        /**
         * Starts the {@link #mUpdateTimeHandler} timer if it should be running and isn't currently
         * or stops it if it shouldn't be running but currently is.
         */
        private void updateTimer() {
            mUpdateTimeHandler.removeMessages(MSG_UPDATE_TIME);
            if (shouldTimerBeRunning()) {
                mUpdateTimeHandler.sendEmptyMessage(MSG_UPDATE_TIME);
            }
        }

        /**
         * Returns whether the {@link #mUpdateTimeHandler} timer should be running. The timer should
         * only run when we're visible and in interactive mode.
         */
        private boolean shouldTimerBeRunning() {
            return isVisible() && !isInAmbientMode();
        }

        /**
         * Handle updating the time periodically in interactive mode.
         */
        private void handleUpdateTimeMessage() {
            invalidate();
            if (shouldTimerBeRunning()) {
                long timeMs = System.currentTimeMillis();
                long delayMs = INTERACTIVE_UPDATE_RATE_MS
                        - (timeMs % INTERACTIVE_UPDATE_RATE_MS);
                mUpdateTimeHandler.sendEmptyMessageDelayed(MSG_UPDATE_TIME, delayMs);
            }
        }
    }

    private static class EngineHandler extends Handler {
        private final WeakReference<CodeProjectWear.Engine> mWeakReference;

        public EngineHandler(CodeProjectWear.Engine reference) {
            mWeakReference = new WeakReference<>(reference);
        }

        @Override
        public void handleMessage(Message msg) {
            CodeProjectWear.Engine engine = mWeakReference.get();
            if (engine != null) {
                switch (msg.what) {
                    case MSG_UPDATE_TIME:
                        engine.handleUpdateTimeMessage();
                        break;
                }
            }
        }
    }
}

This code is also present in the source code that is packaged along with the article. Finally, the manifest for this one was edited as following. The manifest holds the information for the face to be drawn and would be used to provide our Wear Face in the list of faces in Android Wear app companion and the device itself. 

<service
     android:name=".CodeProjectWear"
     android:label="CodeProject Wear"
     android:permission="android.permission.BIND_WALLPAPER" >
     <meta-data
         android:name="android.service.wallpaper"
         android:resource="@xml/watch_face" />
     <meta-data
         android:name="com.google.android.wearable.watchface.preview"
         android:resource="@drawable/preview_analog" />
     <meta-data
         android:name="com.google.android.wearable.watchface.preview_circular"
         android:resource="@drawable/preview_analog" />

     <intent-filter>
         <action android:name="android.service.wallpaper.WallpaperService" />

         <category android:name="com.google.android.wearable.watchface.category.WATCH_FACE" />
     </intent-filter>
</service>

Go ahead and download the source code package provided and test it in your own environment! :-) 

Points of Interest

In this article you have seen how to create a Watch Face, a Watch Face is simply a service that renders objects on the screen for the watch. There are not much facilities provided, but the Canvas is provided which can be used to draw objects. 

There is no TL;DR for the article, I hope you would not feel bored by reading it fully! :-) 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Pakistan Pakistan
Afzaal Ahmad Zeeshan is a computer programmer from Rabwah, Pakistan, currently living in The Netherlands, likes .NET Core and Node.js for regular everyday development. Afzaal Ahmad works at Adyen as a Developer Advocate.

He is an expert with Cloud, Mobile, and API development. Afzaal has experience with the Azure platform and likes to build cross-platform libraries/software with .NET Core. Afzaal is an Alibaba Cloud MVP, twice he has been awarded Microsoft MVP status for his community leadership in software development, four times CodeProject MVP status for technical writing and mentoring, and 4 times C# Corner MVP status in the same field.

Comments and Discussions

 
QuestionSettings panel Pin
Member 1270600426-Aug-16 20:46
MemberMember 1270600426-Aug-16 20:46 
AnswerRe: Settings panel Pin
Afzaal Ahmad Zeeshan27-Aug-16 9:36
mveAfzaal Ahmad Zeeshan27-Aug-16 9:36 
GeneralRe: Settings panel Pin
Member 1270600428-Aug-16 2:10
MemberMember 1270600428-Aug-16 2:10 
QuestionGreat Article Pin
Santhakumar M25-Sep-15 22:47
professionalSanthakumar M25-Sep-15 22:47 
AnswerRe: Great Article Pin
Afzaal Ahmad Zeeshan25-Sep-15 22:54
mveAfzaal Ahmad Zeeshan25-Sep-15 22:54 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.