widget入门

widget就是android桌面小空间.

开发流程大概是:

1.在manifest中注册监听widget更新:

<receiver
            android:name="com.widget.WidgetProvider"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>

            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/widget_confige" />//配置信息
        </receiver>

 2.在res/下新建xml文件夹,在其下新建配置文件,名称为widget_confige(任意命)配置信息如下:

<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:initialLayout="@layout/widget_layout"
    android:minHeight="72dp"
    android:minWidth="72dp"
    android:updatePeriodMillis="3000" >

</appwidget-provider>

 3.新建类继承appwidgetProvider类,重写onupdate方法:

package com.widget;

import java.util.Calendar;

import com.example.widgetdemo.R;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;

//主要继承这个类appwidgetProvider
//onupdate方法
public class WidgetProvider extends AppWidgetProvider {
	private String[] Months = { "一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月",
			"九月", "十月", "十一月", "十二月" };

	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		super.onReceive(context, intent);
	}

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {
		// TODO Auto-generated method stub
		RemoteViews updateViews = buildUpdate(context);
		appWidgetManager.updateAppWidget(appWidgetIds, updateViews);
		
		super.onUpdate(context, appWidgetManager, appWidgetIds);
	}

	private RemoteViews buildUpdate(Context context) {
		RemoteViews updateViews = null;
		Calendar calendar = Calendar.getInstance();
		String months = Months[calendar.get(Calendar.MONTH)];
		//获取widget布局
		updateViews = new RemoteViews(context.getPackageName(),
				R.layout.widget_layout);
		//为布局空间设置内容
		updateViews.setTextViewText(R.id.Month, months);
		updateViews.setTextViewText(R.id.Date,
				String.valueOf(calendar.get(Calendar.DATE)));
		//点击控件跳转到指定activity
		Intent i = new Intent();
		i.setComponent(new ComponentName("com.example.widgetdemo",
				"com.example.widgetdemo.MainActivity"));
		i.setAction(Intent.ACTION_MAIN);
		i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
				| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
		i.addCategory(Intent.CATEGORY_LAUNCHER);
		PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, i,
				0);
		updateViews.setOnClickPendingIntent(R.id.bt, pendingIntent);
		return updateViews;
	}
}

相关推荐