Self-updating every 10 seconds of the Handler.postDelayed problem widget

I am trying to make work self-updating functionality in Android widgets, something as simple as changing two TextViews of it every 10 seconds. An ideal solution would be to make it look like a gin widget (news and weather). And so far it has been working fine: it is updated every 10 seconds using Handler.postDelayed Runnable.

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

The launch starts first in the onUpdate method of my Widget class:

    @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
}

I put this in case someone finds it useful.

: ( ), TextViews , . , , , PostDelayed, updateAppWidget. , : http://thinkandroid.wordpress.com/2010/01/24/handling-screen-off-and-screen-on-intents/ , , , postDelayed, . , , .

, : ?

+3
1

postDelayed if (screenEnabled), , screenEnabled .

+2

Source: https://habr.com/ru/post/1777403/


All Articles