(八)Android Widget开发案例(世界杯倒计时!)

最后更新于:2022-04-01 19:45:51

今天我们要写一下Android Widget的开发,由于快点凌晨,我就不说的太具体了,同志们就模仿吧!首先看一下效果图:   ![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-08-10_57aae596eaffe.gif)   下面是Demo的详细步骤:   一、新建一个Android工程命名为:WidgetDemo.   二、准备素材,一个是Widget的图标,一个是Widget的背景。存放目录如下图:   ![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-08-10_57aae5971e1d4.gif)   三、修改string.xml文件如下: ~~~ Hello World, WidetDemo! DaysToWorldCup   ~~~ 四、建立Widget内容提供者文件,我们在res下建立xml文件夹,并且新建一个widget_provider.xml代码入下:   ~~~ ~~~   五、修改main.xml布局,代码如下:   ~~~ ~~~   六、修改WidgetDemo.java代码如下: ~~~ package com.android.tutor;import java.util.Calendar;import java.util.Date;import java.util.GregorianCalendar;import java.util.Timer;import java.util.TimerTask;import android.appwidget.AppWidgetManager;import android.appwidget.AppWidgetProvider;import android.content.ComponentName;import android.content.Context;import android.widget.RemoteViews;public class WidetDemo extends AppWidgetProvider { /** Called when the activity is first created. */ @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { Timer timer = new Timer(); timer.scheduleAtFixedRate(new MyTime(context,appWidgetManager), 1, 60000); super.onUpdate(context, appWidgetManager, appWidgetIds); } private class MyTime extends TimerTask{ RemoteViews remoteViews; AppWidgetManager appWidgetManager; ComponentName thisWidget; public MyTime(Context context,AppWidgetManager appWidgetManager){ this.appWidgetManager = appWidgetManager; remoteViews = new RemoteViews(context.getPackageName(),R.layout.main); thisWidget = new ComponentName(context,WidetDemo.class); } public void run() { Date date = new Date(); Calendar calendar = new GregorianCalendar(2010,06,11); long days = (((calendar.getTimeInMillis()-date.getTime())/1000))/86400; remoteViews.setTextViewText(R.id.wordcup, "距离南非世界杯还有" + days+"天"); appWidgetManager.updateAppWidget(thisWidget, remoteViews); } } } ~~~   七、修改配置文件AndroidManifest.xml,代码如下: ~~~ ~~~   八、点击运行(Ctrl+F11),之,运行成功后,我们长时间点击桌面,会出现如下俩个,依次点击,就可以看到最上面的效果图:   ![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-08-10_57aae5973a829.gif) ![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-08-10_57aae59751947.gif)   今天就到这里了,我困了呵呵,我发现时间好像不对劲,lol~我也不去多想了,大家知道的告诉我下!对日历这些东西不是太了解,谢谢!!
';