1.桌面小组件的创建流程:
a.绘制widget的布局,配置widget的基本属性,要注意支持的布局,布局大小(布局的长宽过大过高屏幕不能显示,)清单文件的注册.
b.自定义一个WidgetProvider,重写其中的主要方法
c.逻辑的处理.主要是时间的实时更新显示
2.代码处理部分:
a.创建widget的布局以及代码部分
b.点击java工程,new--->widget--->app widget--->创建appWidget.自定义类名,展示的方式,以及宽高.创建完成后,会在java工程目录下生成一个xml文件夹,文件夹中已经为我们自定生成了继承自AppWidgetProvider的类.
c.widget布局文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#09C"
android:padding="@dimen/widget_margin">
<TextView
android:id="@+id/appwidget_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_margin="8dp"
android:background="#09C"
android:contentDescription="显示时间"
android:text="显示时间"
android:textColor="#ffffff"
android:textSize="24sp"
android:textStyle="bold|italic" />
</RelativeLayout>
d.在自定义的NewAppWidget类中重写onUpdate(),onEnabled(),onDisabled()方法.分别完成各自的逻辑.
e.定时器无时无刻的都在运行,所以我们要创建一个service.在服务中完成定时器的不断的更新变换.(注意别忘了service的注册)
public class TimeService extends Service{
private Timer timer;
private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
// 在子线程中不断地更新时间
updateView();
}
}, 0, 1000);
}
private void updateView() {
String time = simpleDateFormat.format(new Date());
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.new_app_widget);
remoteViews.setTextViewText(R.id.appwidget_text, time);
AppWidgetManager manager = AppWidgetManager.getInstance(getApplicationContext());
// ComponentName 从上下文和类对象中创建一个组件标识符
ComponentName componentName = new ComponentName(getApplicationContext(), NewAppWidget.class);
// 更新widget.
manager.updateAppWidget(componentName,remoteViews);
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
f.对主要的类进行解释(最好自己家打开api看看每一个类以及用到的方法)
Timer :相当于定时器.每隔一段时间去执行一个任务.
SimpleDateFormat :日期格式化的一个类.可以格式化各种各样的日期显示格式
RemoteViews :官方文档的解释A class that describes a view hierarchy that can be displayed in another process. The hierarchy is inflated from a layout resource file, and this class provides some basic operations for modifying the content of the inflated hierarchy. 可以在另一个进程中显示的视图层次结构.我自己理解的是将widget的布局填充到桌面上进行显示的一个类.
AppWidgetManager :AppWidget的一个管理类.
ComponentName :组件的标识符类.从上下文和类对象中创建一个组件标识符