I'm trying to implement the update of the widget on a timer.

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

  1. When starting the device;
  2. When you remove and re-add the widget.

The problem is reproduced on both the device and the emulator. I use 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> 

Already tried a lot. Including some solutions from this site, but so far to no avail.

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

    1 answer 1

    In general, figured out on their own. This problem, as it turned out, is easily solved with a simple timer.

    Details.

    Create a class member - an instance of Timer .

     Timer myTimer = new Timer(); 

    We register in it update widget. For example:

     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, start the timer from onUpdate.

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

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