java – Android. Application widget is not updating

Question:

I am trying to implement a timer update of the widget.

As a result, the widget is updated only in two cases:

  1. When the device starts up;
  2. When deleting and re-adding a widget.

The problem is reproducible on both the device and the emulator. I am using Android 4.2.2.

Widget code.

Java

private static String getDate() {
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy hh:mm:ss");
    return dateFormat.format(new Date());
}

public static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,int appWidgetId) {
    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.info_widget);
    views.setTextViewText(R.id.appwidget_textHeader, getDate());
    appWidgetManager.updateAppWidget(appWidgetId, views);
}

public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    super.onUpdate(context,appWidgetManager,appWidgetIds);
    updateAppWidget(context,appWidgetManager,appWidgetIds[0]);
}

XML

<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:initialKeyguardLayout="@layout/info_widget"
    android:initialLayout="@layout/info_widget"
    android:minHeight="40dp"
    android:minWidth="110dp"
    android:previewImage="@drawable/example_appwidget_preview"
    android:resizeMode="horizontal|vertical"
    android:updatePeriodMillis="5000"
    >
</appwidget-provider>

I've tried a lot already. Including some solutions from this site, but so far to no avail.

However, it is likely that I am doing something wrong.

Answer:

In general, I figured it out on my own. This problem turned out to be easily solved with a simple timer.

Details.

We create a member of the class – an instance of Timer .

Timer myTimer = new Timer();

We register the update of the widget in it. For example, like this:

private void startTimer(final Context context, final AppWidgetManager appWidgetManager,
                            final int appWidgetId) {
        myTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                updateAppWidget(context, appWidgetManager, appWidgetId);
            }
        }, 0, 2000);
}

After that, we start the timer from onUpdate.

public void onUpdate(Context context, AppWidgetManager appWidgetManager,
    int[] appWidgetIds) {
            super.onUpdate(context, appWidgetManager, appWidgetIds);                
            startTimer(context, appWidgetManager, appWidgetIds[0]);
}

The information in the widget will be updated every time after a certain time interval (in this example, 2 seconds).

PS Of course, do not forget to stop the timer when it is no longer needed.

public void onDisabled(Context context) {
    myTimer.cancel();
}
Scroll to Top