2010-11-29 135 views
3

我正在尝试使工作成为Android小部件中的自我更新功能,这很简单,因为每10秒更改两个TextView。理想的解决方案是使它类似于精灵小部件(新闻&天气)。到目前为止,它可以正常工作:它通过Handler.postDelayed的Runnable每10秒更新一次。每10秒更新一次自我更新部件Handler.postDelayed问题

Runnable updateWidgetText = new Runnable() 
{ 
    @Override 
    public void run() { 
     if (screenEnabled) { 
      AppWidgetManager gm = AppWidgetManager.getInstance(ctx);       
      ComponentName thisWidget = new ComponentName(ctx,AnimeUndergroundWidget.class);   

      int index = (int)(REFRESH_COUNT % WIDGET_NEWS_TO_SHOW); 
      Noticia n = AUnder.single().getNoticiaByIndex(index); 
      if (n!=null) 
      { 
       last = n; 
       RemoteViews views = new RemoteViews(ctx.getPackageName(),R.layout.auwidget);  
       views.setTextViewText(R.id.widget_textview, n.getTitulo()); 
       views.setTextViewText(R.id.widget_textototal, n.getTexto().replace("\n", "")); 

       Intent clickintent = new Intent(INTENT_GO_TO_NEW); 
       PendingIntent pendingIntentClick = PendingIntent.getBroadcast(ctx, 0, clickintent, 0); 
       views.setOnClickPendingIntent(R.id.widget_fondo_titulo, pendingIntentClick); 

       Intent click2intent = new Intent(INTENT_GO_TO_NEW); 
       PendingIntent pendingIntentClick2 = PendingIntent.getBroadcast(ctx, 0, click2intent, 0); 
       views.setOnClickPendingIntent(R.id.widget_fondo_Texto, pendingIntentClick2); 

       gm.updateAppWidget(thisWidget, views); 
      } 
      REFRESH_COUNT++; 
     } 

     handler.removeCallbacks(this); 
     handler.postDelayed(this, WIDGET_REFRESH_TIME*1000); 
    } 
}; 

可运行在我的Widget类的方法的onUpdate最初推出:

@Override 
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { 

    ctx = context; 
    context.startService(new Intent(context, UpdateWidgetService.class)); 
    handler.postDelayed(updateWidgetText,WIDGET_REFRESH_TIME*1000); 
// here goes some more code, updating the views and refreshing click intents 
} 

我把这个情况下,有人认为它有用。但是让我直接指出:当我把手机从睡眠中打开(打开屏幕)时,小部件会变得疯狂并开始改变TextViews,使其类似于类似快速前进的效果。 我认为这是因为队列中有一些postDelayed事件,或者可能在updateAppWidget队列中。 我已经尝试了一个解决方法,使用这里显示的代码:http://thinkandroid.wordpress.com/2010/01/24/handling-screen-off-and-screen-on-intents/ 你可以在我的代码的第一个片段中看到它,我检查一个存储屏幕状态的布尔变量,以避免在屏幕关闭时使用postDelayed。但这似乎并没有解决它。

这个问题让我疯狂了一个星期了,所以我问出了绝望:有什么办法可以做到这一点吗?

+0

我也试图与定制意图,但结果是一样的。有没有人有这个问题,像FF一样的影响? – 2010-11-30 12:28:43

回答

2

你postDelayed呼叫不是你的,如果(screenEnabled)块内,因此它会继续张贴的事件,即使screenEnabled是假

+0

不敢相信我没有注意到它... – 2011-03-15 06:22:13