Search code examples
androidwidgetalarmmanager

Android - Is widget already on homescreen? Is alarm running?


I am trying to make a widget, where its update frequency can be defined by user and changed at runtime. I can do that using alarm manager, however, is there a way to change the interval of the alarm once its set?

If not, I can still cancel it and start it again with new interval, however I dont know how will this work because widget might not even be added to the homescreen, so the question is, is there a way to know if an alarm is running or better, widget is on homescreen?

Thanks

// EDIT How to determine if your widget exists

private boolean widgetExists() {
    ComponentName myWidget = new ComponentName(this, MyWidgetProvider.class);
    int[] ids = AppWidgetManager.getInstance(this).getAppWidgetIds(myWidget);
    return ids.length > 0;
}

Solution

  • is there a way to change the interval of the alarm once its set?

    For this one, we can reference the docs for AlarmManager.setRepeating():

    Schedule a repeating alarm... If there is already an alarm scheduled for the same IntentSender, it will first be canceled.

    In other words, setting an alarm with the same type cancels the existing interval and resets the alarm with the new values.


    is there a way to know if an alarm is running or better, widget is on homescreen?

    This is the job of AppWidgetProvider. The callbacks in your provider (onEnabled, onUpdate, etc.) can be used to determine the state of whether any widgets are actually active (AppWidgetProvider docs).