Search code examples
androidclickandroid-appwidgetandroid-pendingintent

Android - how can I handle restarts of appWidgets containers?


I'm creating both an appWidget container and appWidgets. I have a problem which I think is because of the created appWidgets - each time I restart (kill and then open) the appWidget container, the appWidget is shown, but it no longer handles clicks.

This occurs on every appWidget container (launchers and even widgetLocker), so that's why I suspect it's because of the appWidget.

I've tried many tutorials online, but I couldn't find any reference about this problem.

Maybe the preparation of the intents (OK, pendingIntents) of the buttons should not be created on the onUpdate method alone? If so, where should I add it? I've added it on the onReceive, but it takes a very long time till that occurs (if at all).

I would have added some code here, but any code online gave me the same results.

How can I fix it?


Solution

  • OK, I am not sure what caused the problem, but here is the solution.

    In short:

    onUpdate(...)
    {
      super.onUpdate(context, appWidgetManager, appWidgetIds);
      for (int appWidgetId: appWidgetIds)
      {
        // Prepare remoteViews, including registration of their clicks events...
        appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
      }
    }
    
    onReceive(...)
    {
      if (intent.getAction().equals(ACTION_BUTTON_CLICKED))
      {
        // Get needed data from the customized intent.
        // Prepare remoteViews of what should be updated, including
        // registration of their clicks events...
        appWidgetManager.updateAppWidget(appWidgetId, remoteViews)
      }
    }