Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

App Widget update TextView

I have been following a tutorial to make Android App Widgets, and I was having a little trouble. The tutorial led me to create this code:

public void onUpdate(Context context, AppWidgetManager appWidgetManager, int [] appWidgetIds) {
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new MyTime(context, appWidgetManager), 1, 1000);
}

private class MyTime extends TimerTask {

    RemoteViews remoteViews;
    AppWidgetManager appWidgetManager;
    ComponentName thisWidget;
    DateFormat format = SimpleDateFormat.getTimeInstance(SimpleDateFormat.MEDIUM, Locale.getDefault());

    public MyTime(Context context, AppWidgetManager appWidgetManager) {
        this.appWidgetManager = appWidgetManager;
        remoteViews = new RemoteViews(context.getPackageName(), R.layout.main);
        thisWidget = new ComponentName(context, FlipWidget.class);
    }

    @Override
    public void run() {
        remoteViews.setTextViewText(R.id.widget_text, "Time: "+format.format(new Date()));
        appWidgetManager.updateAppWidget(thisWidget, remoteViews);
    }
}

but it seems that the run method is never being called, as the TextView never changes. Thanks for your help, I'd love to get a handle on App Widgets.

Nick

like image 963
Nick Avatar asked Apr 01 '26 02:04

Nick


1 Answers

First, you cannot use Timer. Your AppWidgetProvider, and the Timer, will be garbage-collected once onUpdate() returns.

Second, please do not update an app widget every second. There is a reason why android:updatePeriodMillis has a 30-minute minimum -- pushing updates to app widgets is an expensive operation. Updating one every second would not only force your "update an app widget" code to effectively be resident in memory and running all of the time, but you will also whack the user's battery pretty significantly.

For periodic updates of an app widget, either use android:updatePeriodMillis or use AlarmManager.

like image 79
CommonsWare Avatar answered Apr 02 '26 20:04

CommonsWare



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!