Creating an app widget in Android for analog clock

0
4076

Widget: App Widgets are miniature application views that can be embedded in other applications (such as the Home screen) and receive periodic updates. These views are referred to as Widgets in the user interface, and you can publish one with an App Widget provider. An application component that is able to hold other App Widgets is called an App Widget host. 

Step 1

Create a new project called “MyClockWidget”

Step 2

Modifying the AndroidManifest.xml as follows

Step 3

Creating Xml files

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).

res/layout/main.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.

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.

Step 4

Creating 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

Widget.java: In order to create and use a widget we must extend AppWidgetProvider. 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.

Step 5

Compile and Run

Picture1

Picture2