今天我们学习如何利用Widget来显示系统当前的日期和时间,下面给出该场景的案例:
1案例技术要点
(1)创建TimeWidgetProvider继承于AppWidgetProvide类,并重写如下两个方法:
onDeleted(...):当第一次向桌面添加Widgets的时候回调此方法 onEnabled(...):当最后一个同类型Widgets实例被删除时回调此方法 (2)创建TimerService继承于Service类,用于获取系统当前日期与时间。 (3)通过获取AppWidgetManager实例将TimerService和TimeWidgetProvider关联起来。2案例代码陈列
AndroidManifest.xml
strings.xml
Lynn时间Widgets
main.xml
Widget布局文件:time_appwidget.xml
Widget背景文件:rectangle.xml
Widget显示内容提供者:TimeWidgetProvider.java
package cn.lynn.widgets;import android.appwidget.AppWidgetManager;import android.appwidget.AppWidgetProvider;import android.content.Context;import android.content.Intent;public class TimeWidgetProvider extends AppWidgetProvider { // 当用户从桌面上删除widgets的时候回调此方法 @Override public void onDeleted(Context context, int[] appWidgetIds) { } // 当第一次向桌面添加Widgets时回调此方法 @Override public void onEnabled(Context context) { context.startService(new Intent(context, TimerService.class)); } // 当最后一个同类型Widgets实例被删除时回调此方法 @Override public void onDisabled(Context context) { context.stopService(new Intent(context, TimerService.class)); } @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { }}
Widget服务管理类:TimerService.java
package cn.lynn.widgets;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Timer;import java.util.TimerTask;import android.app.PendingIntent;import android.app.Service;import android.appwidget.AppWidgetManager;import android.content.ComponentName;import android.content.Intent;import android.net.Uri;import android.os.IBinder;import android.widget.RemoteViews;public class TimerService extends Service { private Timer timer; @Override public void onCreate() { super.onCreate(); timer = new Timer(); timer.schedule(new TimeUpdateWork(), 0, 1000); } private final class TimeUpdateWork extends TimerTask{ public void run() { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String time = dateFormat.format(new Date()); RemoteViews remoteView = new RemoteViews(getPackageName(), R.layout.time_appwidget); remoteView.setTextViewText(R.id.textView, time); // 拨号意图 PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 100, new Intent(Intent.ACTION_CALL, Uri.parse("tel:18777777777")), 0); // 点击Widget拨打号码:18777777777 remoteView.setOnClickPendingIntent(R.id.textView, pendingIntent); AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getApplicationContext()); appWidgetManager.updateAppWidget(new ComponentName(getApplicationContext(), TimeWidgetProvider.class), remoteView); } } @Override public void onDestroy() { timer.cancel(); timer = null; super.onDestroy(); } @Override public IBinder onBind(Intent intent) { return null; }}