K
K
kirvel2021-09-05 20:59:32
Java
kirvel, 2021-09-05 20:59:32

How to update a widget in Android at a given time using AlarmManager?

I have a widget that needs to be updated every day at a given time. I tried to implement this via AlarmManager but the widget is not updating.

@Override
public void onReceive(Context context, Intent intent) {
    super.onReceive(context, intent);

    if (ACTION_AUTO_UPDATE_WIDGET.equals(intent.getAction())) {
        onUpdate(context, AppWidgetManager.getInstance(context),
                
    AppWidgetManager.getInstance(context).getAppWidgetIds(newComponentName(context, Widget.class)));
    }
}

@Override
public void onDisabled(Context context) {
    super.onDisabled(context);
    Intent intent = new Intent(Widget.ACTION_AUTO_UPDATE_WIDGET);
    AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmMgr.cancel(PendingIntent.getBroadcast(context, 0, intent, 0));
}

@Override
public void onEnabled(Context context) {
    super.onEnabled(context);

    Intent intent = new Intent(Widget.ACTION_AUTO_UPDATE_WIDGET);
    PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

    Calendar c = Calendar.getInstance();
    c.set(Calendar.HOUR_OF_DAY, 17);
    c.set(Calendar.MINUTE, 32);
    c.set(Calendar.SECOND, 0);

    AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmMgr.setRepeating(AlarmManager.RTC, c.getTimeInMillis(), AlarmManager.INTERVAL_DAY, alarmIntent);
}

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    for (int id : appWidgetIds) {
        updateWidget(context, appWidgetManager, id);
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
kirvel, 2021-09-07
@kirvel

The problem was that I was creating the Intent incorrectly. Here's how it should have been:

Intent intent = new Intent(context, Widget.class);
intent.setAction(ACTION_AUTO_UPDATE_WIDGET);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question