Android AppWidgetProvider使用简例

AppWidgetProvider是一个BroadcastReceiver,必须在AndroidManifest.xml中声明该Receiver,并接收“Android.appwidget.action.APPWIDGET_UPDATE”。AppWidgetProvider使开发者能够自定义的桌面小工具。本文介绍一个桌面时钟的小工具。用户安装程序后需要在手机窗口小工具中添加,方可查看到。

继承AppWidgetProvider类,实现update方法。

package com.example.desktopdemo;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.annotation.SuppressLint;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.widget.RemoteViews;

public class EX04_28 extends AppWidgetProvider {

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {
		Intent intent = new Intent(context, UpdateService.class);
		context.startService(intent);
		super.onUpdate(context, appWidgetManager, appWidgetIds);
	}

	public static class UpdateService extends Service {

		@Override
		public IBinder onBind(Intent intent) {
			// TODO Auto-generated method stub
			return null;
		}

		@SuppressLint("SimpleDateFormat") @Override
		public void onStart(Intent intent,int startId){
		RemoteViews updateViews = new RemoteViews(this.getPackageName(),R.layout.main);
		SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
		updateViews.setTextViewText(R.id.textView01, ""+sdf.format((new Date())));
		ComponentName thisWidget = new ComponentName(this,EX04_28.class);
		AppWidgetManager manager = AppWidgetManager.getInstance(this);
		manager.updateAppWidget(thisWidget, updateViews);
		}
	}

}

AndroidManifest.xml的定义




    

    
        
            
                
            
            
            
        
        
    


my_widget_provider.xml定义(注:android:updatePeriodMillis 这种方式已经在SKD1.5以后被废了,可自定义线程进行刷新



main.xml定义:




    


Demo下载

你可能感兴趣的:(android)