Android Desktop Widget Development Essentials resolution (Time and date widget) _android

Source: Internet
Author: User
Tags time and date

Desktop widgets that recently need to write a DateTime are used to associate calendar programs, and desktop widgets have rarely been written before. Not very familiar with this technique, take the time to rearrange it today, and write down a simple time and date process.

The Desktop widget is a tool for displaying some information (some widgets are now being developed with practical functions.) For example, a camera widget that can be photographed directly on the desktop. Overall, however, the widget's main function is to display some information. Today we write a very simple widget that displays information such as time, date, and day of the week. To display time information, you need to update it in real time, one second or one minute.

This time widget I am referring to (the Android application development) book inside a demo example to do, but to improve the function and interface. Here is the effect chart:



1. Inherit Appwidgetprovider
The Desktop widget we write needs to provide a data update, which requires Appwidgetprovider, which has some system callback functions. Provides an operation to update data. Appwidgetprovider is brocastreceiver, which means that it is actually a broadcast receiver. Let's look at several important callback methods for Appwidgetprovider:

Copy Code code as follows:

Class Widgetprovider extends Appwidgetprovider
{
private static final String tag= "Mythou_widget_tag";
Call once without receiving a broadcast message, use frequently
public void OnReceive (context context, Intent Intent)
{
LOG.D (TAG, "Mythou--------->onreceive");
Super.onreceive (context, intent);
}

This method is called once per update and is used frequently
public void OnUpdate (context context, Appwidgetmanager Appwidgetmanager, int[] appwidgetids)
{
LOG.D (TAG, "Mythou--------->onupdate");
Super.onupdate (context, Appwidgetmanager, appwidgetids);
}

Call once without deleting one
public void ondeleted (context context, int[] appwidgetids)
{
LOG.D (TAG, "Mythou--------->ondeleted");
Super.ondeleted (context, appwidgetids);
}

When the widget is first added to the desktop, the method is called and can be added multiple times but only for the first time
public void onenabled
{
LOG.D (TAG, "Mythou--------->onenabled");
super.onenabled (context);
}

When the last widget deletion is calling the method, note that the last one
public void ondisabled
{
LOG.D (TAG, "Mythou--------->ondisabled");
super.ondisabled (context);
}
}

Among them, we are more commonly used onupdate and OnDelete methods. I am here to refresh the time using a service, because to refresh services regularly, also need a alarm timer service. Here's my OnUpdate method:
Copy Code code as follows:

public void OnUpdate (context context, Appwidgetmanager Appwidgetmanager, int[] appwidgetids)
{
Super.onupdate (context, Appwidgetmanager, appwidgetids);
Time is = new Time ();
Time.settonow ();
Update time using Service
Intent Intent = new Intent (context, updateservice.class);
Pendingintent pendingintent = pendingintent.getservice (context, 0, intent, 0);
Update interface data using alarm timing
Alarmmanager alarm = (Alarmmanager) context.getsystemservice (Context.alarm_service);
Alarm.setrepeating (ALARMMANAGER.RTC, Time.tomillis (True), 60*1000, pendingintent);
}

2, Androidmanifest.xml configuration
Copy Code code as follows:

<application
android:icon= "@drawable/icon"
Android:label= "@string/app_name" >
<!--Appwidgetprovider Registration mythou-->
<receiver
Android:label= "@string/app_name_timewidget"
Android:name= "Com.owl.mythou.TimeWidget" >
<intent-filter>
<action android:name= "Android.appwidget.action.APPWIDGET_UPDATE" ></action>
</intent-filter>
<meta-data
Android:name= "Android.appwidget.provider"
Android:resource= "@xml/time_widget_config" >
</meta-data>
</receiver>
<!--background service for update time mythou-->
<service android:name= "Com.owl.mythou.UpdateService" ></service>

</application>

Androidmanifest is primarily configured with a receiver, because Appwidgetprovider is a broadcast receiver. Also note that you need to provide an action, which is the system's Update widget action. There are also meta-data that need to specify the widget's configuration file. This configuration file needs to be placed under the Res\xml directory, let's look at the configuration of Time_widget_config.xml

3, Appwidget configuration:
Copy Code code as follows:

<?xml version= "1.0" encoding= "Utf-8"?>
<appwidget-provider
Xmlns:android= "Http://schemas.android.com/apk/res/android"
android:initiallayout= "@layout/time_widget_layout"
Android:minwidth= "286dip"
android:minheight= "142dip"
android:updateperiodmillis= "0" >
</appwidget-provider>

android:initiallayout The layout file that specifies the layout of the interface, as with the layout of the activity
android:minwidth The minimum width of your widget. Based on the layout cell (72* lattice number-2)
Android:minheigh The minimum height of your widget. The method is the same as MinWidth. (Do not know about this can see me launcher analysis article)
Android:updateperiomillis Use System Timer update service, in milliseconds.

Here need to explain the problem of Android:updateperiomillis, the system to save electricity, the default is 30 minutes update, if you set the value of less than 30 minutes, the system is 30 minutes will be updated. For us to make time widgets, obviously not reliable. So you can only write a alarm timer service update.

4. Update Widget Service

Copy Code code as follows:

Class Updateservice extends Service
{
@Override
public void OnStart (Intent Intent, int startid)
{
Super.onstart (Intent, Startid);
Updatewidget (this);
}
private void Updatewidget (context context)
{
Less CPU load without calendar,time
Time is = new Time ();
Time.settonow ();
int hour = Time.hour;
int min = Time.minute;
int second = Time.second;
int year = Time.year;
int month = time.month+1;
int day = Time.monthday;
String strtime = String.Format ("%02d:%02d:%02d%04d-%02d-%02d", Hour, Min, second,year,month,day);
Remoteviews Updateview = new Remoteviews (Context.getpackagename (),
R.layout.time_widget_layout);

Time image Update
String packagestring= "Org.owl.mythou";
String timepic= "Time";
int hourhbit = HOUR/10;
Updateview.setimageviewresource (R.id.hourhpic, Getresources (). Getidentifier (Timepic+hourhbit, "drawable", packagestring));
int hourlbit = hour%10;
Updateview.setimageviewresource (R.id.hourlpic, Getresources (). Getidentifier (Timepic+hourlbit, "drawable", packagestring));
int minhbit = MIN/10;
Updateview.setimageviewresource (R.id.minutehpic, Getresources (). Getidentifier (Timepic+minhbit, "drawable", packagestring));
int minlbit = min%10;
Updateview.setimageviewresource (R.id.minutelpic, Getresources (). Getidentifier (Timepic+minlbit, "drawable", packagestring));

Day of the Week
Updateview.settextviewtext (R.id.weekinfo, getweekstring (time.weekday+1));

Date updated, calculated using the picture according to the date
String datepic= "Date";
int year1bit = year/1000;
Updateview.setimageviewresource (R.id.year1bitpic, Getresources (). Getidentifier (Datepic+year1bit, "drawable", packagestring));
int year2bit = (year%1000)/100;
Updateview.setimageviewresource (R.id.year2bitpic, Getresources (). Getidentifier (Datepic+year2bit, "drawable", packagestring));
int year3bit = (year%100)/10;
Updateview.setimageviewresource (R.id.year3bitpic, Getresources (). Getidentifier (Datepic+year3bit, "drawable", packagestring));
int year4bit = year%10;
Updateview.setimageviewresource (R.id.year4bitpic, Getresources (). Getidentifier (Datepic+year4bit, "drawable", packagestring));
Month
int mouth1bit = MONTH/10;
Updateview.setimageviewresource (R.id.mouth1bitpic, Getresources (). Getidentifier (Datepic+mouth1bit, "drawable", packagestring));
int mouth2bit = month%10;
Updateview.setimageviewresource (R.id.mouth2bitpic, Getresources (). Getidentifier (Datepic+mouth2bit, "drawable", packagestring));
Day
int day1bit = DAY/10;
Updateview.setimageviewresource (R.id.day1bitpic, Getresources (). Getidentifier (Datepic+day1bit, "drawable", packagestring));
int day2bit = day%10;
Updateview.setimageviewresource (R.id.day2bitpic, Getresources (). Getidentifier (Datepic+day2bit, "drawable", packagestring));

Click Widget to start the calendar
Intent launchintent = new Intent ();
Launchintent.setcomponent (New ComponentName ("Com.mythou.mycalendar"),
"Com.mythou.mycalendar.calendarMainActivity"));
Launchintent.setaction (Intent.action_main);
Launchintent.addcategory (Intent.category_launcher);
Launchintent.setflags (Intent.flag_activity_new_task
| intent.flag_activity_reset_task_if_needed);
Pendingintent intentaction = pendingintent.getactivity (context, 0,
Launchintent, 0);
Updateview.setonclickpendingintent (R.id.smallbase, intentaction);
Appwidgetmanager AWG = appwidgetmanager.getinstance (context);
Awg.updateappwidget (New ComponentName (context, Timewidgetsmall.class),
Updateview);
}
}

The above is my service, because my interface time and date are done using pictures (purely for the sake of looking at the point). So many more than the time and date to calculate the use of the picture name code, these are personal actual processing, here is not much to say.
one thing that needs to be explained is remoteviews.
Copy Code code as follows:

Remoteviews Updateview = new Remoteviews (Context.getpackagename (), r.layout.time_widget_layout);

Generate a remote views update object from our interface profile, which can manipulate other processes in different processes. Because widgets are run in the process of launcher, not an independent process. This is also a remote access mechanism. The last is to add a click on the desktop widget to start a program function, but also using the Pendingintent method.

Writing a desktop Widget is basically just these steps, and finally add that the desktop Widget interface layout only supports some of the standard Android controls, and if you need to do a complex widget interface, you need to customize the control. There's time to talk about this part later.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.