每10秒自我更新一次widget Handler.postDelayed问题

时间:2010-11-29 08:40:51

标签: android android-widget postdelayed

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

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);
    }   
};  

runnable最初是在我的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。但这似乎没有解决它。

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

1 个答案:

答案 0 :(得分:2)

您的postDelayed调用不在if(screenEnabled)块内,因此即使screenEnabled为false,它也会继续发布事件