App Widget TextView Update

I am following a tutorial on creating widgets for Android apps, and I had some minor issues. 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 called, since the TextView never changes. Thanks for your help, I'd love to look at App Widgets.

Nick

+3
source share
1 answer

Firstly, you cannot use Timer. Yours AppWidgetProviderand Timerwill collect garbage after return onUpdate().

-, . , android:updatePeriodMillis 30- - - . " " , .

android:updatePeriodMillis AlarmManager.

+3

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


All Articles