widget.xml
widgetconfig.xml
android:updatePerioMillis 使用系统定时更新服务,单位毫秒。
这里需要说明android:updatePerioMillis的问题,系统为了省电,默认是30分钟更新一次,如果你设置的值比30分钟小,系统也是30分钟才会更新一次
TimerService.java
public class TimerService extends Service{ private Timer timer; private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); @Override public IBinder onBind(Intent arg0) { return null; } @Override public void onCreate() { super.onCreate(); timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { updateView(); } }, 1, 1000); } private void updateView(){ String time = sdf.format(new Date()); RemoteViews rv = new RemoteViews(getPackageName(), R.layout.widget); rv.setTextViewText(R.id.tv, time); AppWidgetManager manager = AppWidgetManager.getInstance(getApplicationContext()); ComponentName cn = new ComponentName(getApplicationContext(), WidgetProvider.class); manager.updateAppWidget(cn, rv); } @Override public void onDestroy() { super.onDestroy(); timer = null;//widget销毁 }}
widgetProvider.java
public class WidgetProvider extends AppWidgetProvider { @Override public void onDeleted(Context context, int[] appWidgetIds) { super.onDeleted(context, appWidgetIds); } @Override public void onEnabled(Context context) { super.onEnabled(context); context.startService(new Intent(context,TimerService.class));//开启服务 } @Override public void onDisabled(Context context) { super.onDisabled(context); context.stopService(new Intent(context,TimerService.class));//停止服务 } @Override public void onReceive(Context context, Intent intent) { super.onReceive(context, intent); } @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { super.onUpdate(context, appWidgetManager, appWidgetIds); }}
AndroidManifest.xml添加关键代码