【问题标题】:Self-updating every 10 seconds widget Handler.postDelayed problem每10秒自更新widget Handler.postDelayed问题
【发布时间】:2011-03-15 03:25:35
【问题描述】:

我正在尝试使工作成为 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/ 您可以在我的代码中的第一个 sn-p 中看到它,我检查了一个已存储屏幕状态的布尔变量,以避免在屏幕关闭时使用 postDelayed。但这似乎并不能解决问题。

这个问题已经让我发疯了一个星期,所以我绝望地问:有什么办法可以正确地做到这一点?

【问题讨论】:

  • 我也尝试过自定义 Intent,但结果是一样的。有没有人遇到过这个问题,类似FF的效果?

标签: android android-widget postdelayed


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2021-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-04
    • 2012-03-26
    • 1970-01-01
    相关资源
    最近更新 更多