package com.genius.col;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.widget.RemoteViews;
public class AppClockWidgetProvider extends AppWidgetProvider{
private static RemoteViews mRemoteViews;
private static Timer mTimer;
// mAppWidgetArray 保存窗口部件实例的数组
private static ArrayList<int[]> mAppWidgetArray = new ArrayList<int[]>();
// 当最后一个窗口部件实例被移除时调用
public void onDisabled(Context context) {
// TODO Auto-generated method stub
super.onDisabled(context);
stopTimerTask();
}
// 当第一个窗口部件实例被创建时调用
public void onEnabled(Context context) {
// TODO Auto-generated method stub
super.onEnabled(context);
startTimerTask(context);
}
// 窗口部件实例创建时调用
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
// TODO Auto-generated method stub
super.onUpdate(context, appWidgetManager, appWidgetIds);
updateAppWidget(context, appWidgetManager, appWidgetIds);
addInstance(appWidgetIds);
}
// 窗口部件实例删除时调用
public void onDeleted(Context context, int[] appWidgetIds) {
// TODO Auto-generated method stub
super.onDeleted(context, appWidgetIds);
removeInstance(appWidgetIds);
}
// 更新单个窗口部件实例
public static void updateAppWidget(Context context,
AppWidgetManager appWidgeManger, int []appWidgetIds) {
mRemoteViews = new RemoteViews(context.getPackageName(), R.layout.main);
MyTimeAdapter timeAdapter = new MyTimeAdapter();
String timeString = timeAdapter.formatTime();
mRemoteViews.setTextViewText(R.id.myTextView, timeString);
appWidgeManger.updateAppWidget(appWidgetIds, mRemoteViews);
}
// 更新所有窗口部件实例
public static void RefreshAllWidget(Context context){
AppWidgetManager appWidgetManger = AppWidgetManager.getInstance(context);
int instanceCount = mAppWidgetArray.size();
for(int i = 0; i < instanceCount; i++){
int[]appWidgetIds = mAppWidgetArray.get(i);
updateAppWidget(context, appWidgetManger, appWidgetIds);
}
}
// 增加窗口部件实例
public static void addInstance(int[] appWidgetIds){
if (mAppWidgetArray != null){
mAppWidgetArray.add(appWidgetIds);
}
}
// 删除窗口部件实例
public static void removeInstance(int[] appWidgetIds){
if (mAppWidgetArray != null){
mAppWidgetArray.remove(appWidgetIds);
}
}
// 开启刷新窗口部件的定时器
public static void startTimerTask(final Context context){
if (mTimer == null){
mTimer = new Timer();
TimerTask mTimerTask = new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
AppClockWidgetProvider.RefreshAllWidget(context);
}
};
mTimer.schedule(mTimerTask, 0, 1000);
}
}
// 关闭刷新窗口部件的定时器
public static void stopTimerTask(){
if (mTimer != null){
mTimer.cancel();
mTimer = null;
}
}
}