Rafael T Rafael T - 1 year ago 105
Android Question

prevent triggering of onUpdate of WidgetProvider

I'm implementing a Widget that has a ConfigurationActivity, and must stay compatible to Eclair(2.1).

The documentation about AppWidgetProviders

method states clearly that:

... .However, if you have declared a configuration Activity, this method is not called when the user adds the App Widget, but is called for the subsequent updates. It is the responsibility of the configuration Activity to perform the first update when configuration is done. (See Creating an App Widget Configuration Activity below.)

Unfortunately this isn't true (at least for my Nexus S with JellyBean). In Fact
gets called before
of my ConfigurationActivity triggers. I want to know, if there is similar behavior on other phones, and if it is possible to prevent the
call inside my Provider?

My Workaround is to store a SharedPreference inside my WidgetConfigurationActivity with that particular AppWidgetId. If it isn't there, I can assume that the ConfigurationActivity wasn't called first. This works, but is in my point of View really ugly. If I cannot prevent
from triggering, is there a better solution?

Answer Source

Yes, onUpdate() gets called when you add a widget on the homescreen. See here:



I'm not sure if there is a way to not trigger it when a widget is created. But you can stop it from triggering again by setting the "updatePeriodMillis" field in Widget Info XML file to 0 or just leaving it blank.

Another way would be to store the widget IDs somewhere. Now whenever a new widget is added, in your Receiver class, check if the ID already exists or not. If it does not exist (meaning a new widget), then dont execute any code. Also, remove widget ID from your records whenever a widget is deleted. Since there is a possibility that you removed a widget, then later added a new widget which has the same ID as the old one.

Hope that helps!

EDIT: In the onReceive() method in your Receiver class, do this:

public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub

    int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
    if( appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID )
        super.onReceive(context, intent);


When a widget is first selected from the Widgets list, its appWidgetId will be equal to INVALID_APPWIDGET_ID until it is added on the home screen. Since "super.onReceive()" calls the onUpdate() method when a widget is selected, onUpdate() will not be called the first time.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download