Programming Android
 All Modules Pages

All app widget instances are managed by a corresponding "widget provider" class:

public class MyWidgetProvider extends AppWidgetProvider

The widget provider class will be triggered by the Android operating system when to refresh all instantiated widgets:

// this method is called in regular time intervals to allow a refresh of the widget's contents
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds)
{
// Get actualized info about next alarm and adjust notification for lock screen
AlarmInfo alarmInfo = CheckForNextAlarm(context);
RefreshNotificationForLockScreen(context, alarmInfo);
// Iterate over all widget instances to actualize their alarm info
final int numWidgets = appWidgetIds.length;
for (int i=0; i < numWidgets; i++) {
int widgetId = appWidgetIds[i];
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.my_widget);
// Actualize text display.
String displayText;
if (alarmInfo.alarmTime.isEmpty())
{
displayText = "\noff";
}
else // alarm is set
{
// Build info text like:
// So. 7:30
// (114 h)
displayText = alarmInfo.alarmTime + " \n(" + alarmInfo.durationUntilAlarm + ")";
}
remoteViews.setTextViewText(R.id.text, displayText);
Intent intent = new Intent(context, MyWidgetProvider.class);
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
// Define a refresh action on button click
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.refreshImageBtn, pendingIntent);
appWidgetManager.updateAppWidget(widgetId,remoteViews);
}
}