THE CLOCK WIDGET
Sup everyone! Happy Holiday to all.This time r2d is back with another cool android project. We are going to make a digital clock widget of our own. Isn't that cool!
Note that Android has an in-built Digital Clock widget in its layouts , but we want more customization so we are implementing our own version of it. So let's roll.
1. Create a new Android Application Project
2. Add a new AppWidgetProvider resource to res/xml
- Create the res/xml folder if not available already.
- Add a new xml to this folder and name it widget_xml.xml (or anything you like).
- Add the code given below to the xml file.The Structure is also shown if figure below.
- The fields are as described below:
- Min Width/Height - min. width/height with which the widget will be drawn.
- Min. Resize Width/Height - width/height to which it can be re-sized.
- Initial layout - the layout which is used to draw the widget.
- Resize Mode - direction in which re-size is allowed.
Fields in the AppWidgetProvider |
3. Make changes to the Manifest XML
- Add the following permissions the manifest file as they will be used to access some features of Android system later while coding.
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
- Remove the <activity> tag from your <application> tag as our app doesn't implement an activity.Instead add a receiver for the widget as shown below:-
Final view of the Project Explorer 4. Code the MainActivity
- The MainActivity extends AppWidgetProvider so that it can use the services of the Android API.
- The various methods such as OnReceive(), OnUpdate() , OnEnabled(), OnDisabled() of the AppWidgetProvider are overridden , to apply widget life cycle methods.
- More in the last section.
--Code Explained --
- The OnReceive() method is called when the widget receives call to update its contents. Here we get all the id(s) for all the instances of our widget , and call updatetime() method the we defined, to update time in every instance.
- The createClockIntent() method is used by the AlarmManager to send a pending Intent to our widget every 1000 msec. The Android system only allows to update a widget every 30min (due to several reasons). So we use Alarm Manager to update it each second.
- The OnEnabled() method is used to start the Alarm Manger and the method OnDisabled() is where the timer is disabled.
- Finally in the OnUpdate() method we acquire a Wake Lock, to keep the CPU on (Note that this is not necessary here ,but I thought to show it's use here). the it uses RemoteViews to send Pending Intent to each TextView to open ALARM Intent. Finally the Wake Lock is released.
- The updatetime() method is just filling the TextViews with the required time and date.
0 comments:
Post a Comment