Andret Andret - 2 months ago 12
Android Question

Android - Widget Intent based on date does not change

My widget provider has intent with value named id, wchich is equal current day of year. But this intent does not change. If today it is focused on 8th March, tomorrow it will also be focused on this day. And on the next day also and so on. But I need to refresh this intent every day.

MyWidgetProvider.java:

public class MyWidgetProvider extends AppWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
int layoutId = R.layout.widget;
Calendar c = Calendar.getInstance();
c.setTime(new Date());
int id = c.get(Calendar.DAY_OF_YEAR);
boolean leap = new GregorianCalendar().isLeapYear(c.get(Calendar.YEAR));
int targetId = id<60?id:id+(leap?0:1);
for (int i:appWidgetIds) {
Intent intent = new Intent(context, MainActivity.class);
intent.putExtra("from", "widget");
intent.putExtra("id", targetId);
intent.putExtra("widgetID", i);
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), layoutId);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
remoteViews.setOnClickPendingIntent(R.id.widget_relative_main, pendingIntent);
}
}
}


my_widget_provider.xml:

<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:initialLayout="@layout/widget"
android:minHeight="31dp"
android:minWidth="72dp"
android:resizeMode="horizontal|vertical"
android:updatePeriodMillis="300000" >

</appwidget-provider>


What is a problem?

Answer

SOLUTION:

There was required PendingIntent flag "FLAG_UPDATE_CURRENT":

PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

And everything works well!

Comments