2012-02-07 56 views
0

我需要创建一个小部件,它会每分钟下载一次sdcard上的一些位图并将它们打印在屏幕上。我试图用下载和打印位图的android小部件不起作用

private class MyTime extends TimerTask 

但是不起作用。该小部件不会更新:( 图像总共有30K。你能帮我解决这个问题吗?我只需要一个代码示例,我可以把这个小部件的代码放在这里。 这是代码:

public class MyWidget extends AppWidgetProvider { 
public int tt=0; 

@Override 
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { 
    if(tt==0) { 
     Timer timer = new Timer(); 
     timer.scheduleAtFixedRate(new MyTime(context, appWidgetManager), 1, 10000); 
     tt=1; 
    } 
} 

private class MyTime extends TimerTask { 

    RemoteViews remoteViews; 
    AppWidgetManager appWidgetManager; 
    long t=0,lastUpdate=0; 
    ComponentName thisWidget; 

    public MyTime(Context context, AppWidgetManager appWidgetManager) { 

     this.appWidgetManager = appWidgetManager; 
     remoteViews = new RemoteViews(context.getPackageName(), R.layout.main); 
     thisWidget = new ComponentName(context, MyWidget.class); 
    } 
    @Override 
    public void run() { 

     DateFormat dateFormat = new SimpleDateFormat("dd/MM HH:mm"); 
     //get current date time with Date() 
     Date date = new Date(); 
    remoteViews.setTextViewText(R.id.Clock,dateFormat.format(date)); 
    appWidgetManager.updateAppWidget(thisWidget, remoteViews); 

     if(t==0 || t + 100000<=System.currentTimeMillis()) { 
      checkUpdate(); 
      display(); 
      t=System.currentTimeMillis(); 
     } 
    } 
+0

“不更新”意味着没有UI更改或失败,错误或什么? – 2012-02-07 08:56:50

+0

它仍然与main.xml中的初始xml – 2012-02-07 09:00:55

+0

相关,您确定您的代码正在运行,并且它应该更改UI状态? – 2012-02-07 09:02:13

回答

0

这可能是失败,因为一个TimerTask在自己的线程中运行,但你不能从不是UI(主)线程以外的任何线程使Android UI库调用。

要运行定时在UI线程上执行操作,分配自己的Handler并使用其调用postDelayed/postAtTime调用。