androidwidgetandroid-widgethome-screen-widget

Android Widgets: Differentiating between initial update and auto-update?


I'm currently developing a widget that requires the user to be logged in. When the user initially adds the widget and they're not logged in, I take them to the login activity so that they can log in. However, I don't want to do that when the widget auto-updates (it would be very annoying to have an app randomly launch when you're just browsing your home screen).

The updating code is currently in onUpdate(), but I haven't been able to figure out how to differentiate between the update that occurs when the widget is initially added and the update that occurs periodically. Is there a way to do this?

To summarize, I'm trying to make the following: - Initial update when user adds the widget: Open login activity - Subsequent periodic updates: Don't open login activity

Note: I'd like to avoid onEnabled(), since that is only called when the FIRST widget is added. I'd like my code to run every time a new widget is added.


Solution

  • If you are looking for just one instance of your widget, then you could go with shared preference boolean to solve this issue.

    onEnabled - Clear boolean

    onUpdate - if boolean not set -> Means first time (Do your work and set the boolean) If boolean is set -> Means its the normal widget update.

    Work around option if you need to deal with multiple widget instances :

    If you need to achieve the above requirement, you need to handle auto update in intervals by your own.

    That means, all the the call towards onUpdate should come from your own created Intents. That is :

    1. Use Alarm manager to trigger the onUpdate functionality of Widget. Add bundle value to intent stating its an update call.
    2. All widget interaction intents should contain the bundle value to say its an update call.
    3. In onUpdate method, check for the same bundle value mentioned above and if its there, its a normal update else BINGO... :)