0

Probably a newbie question. I have tried playing with android AppWidgetProvider onUpdate method and using "sleep" to induce a small delay.

The update is repeated using a loop - here is the thing: with the loop counter set to 20 and sleep time one second - loop only executes 10 times - 900 millsec a second delay increase loop to 12 and delay of 500 mills gets the full loop count of 20. How is this explained?

See the AppWidgetProvide code below. The widget simply contains one textview only.

public class SimpleWidget extends AppWidgetProvider {

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
            int[] appWidgetIds) {
        // TODO Auto-generated method stub
        super.onUpdate(context, appWidgetManager, appWidgetIds);
        Log.w("on update here", " message");
        RemoteViews rm = new RemoteViews(context.getPackageName(),
                R.layout.widget_layout);
        for (int loop = 0; loop <= 20; loop++) {
            Log.w("on update here", "loop counter  =" + loop);
            rm.setTextViewText(R.id.tvWidget, "now you see it " + loop);
            for (int index = 0; index < appWidgetIds.length; index++) {

                appWidgetManager.updateAppWidget(appWidgetIds[index], rm);
                Log.w("updating", "aw number  =" + index);
            }
            try {
                Thread.sleep(2000, 0);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }
shermy
  • 1
  • 3

1 Answers1

0

You will note that the time comes close to 10 seconds in all cases. This is because an AppWidgetProvider is just a convenience class. It simply wraps around a BroadcastReceiver and interprets the widgets broadcasts, then it calls the appropriate methods (onUpdate() and so on).

And a BroadcastReceiver has to finish processing a broadcast within 10 seconds, otherwise you get an ANR.

Which means that using Thread.sleep() is a bad idea here. Simply don't do that.

It's not entirely clear what you are trying to do here to me. If you want to update your widget every X seconds, rather use the AlarmManager and schedule the update intent broadcast on a regular interval or start a new Thread to do the timings.