AppWidgetManager getAppWidgetIds returning old Widget ids

有些话、适合烂在心里 提交于 2019-12-03 11:21:54

问题


I'm trying to get a list of all ACTIVE instances of my widget. In the OnUpdate method of my AppWidgetProvider, I'm doing the following:

// Get all ids
ComponentName thisWidget = new ComponentName(context, this.getClass());
int[] lastWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);

The problem is that if you add a widget to your homescreen and then delete it, getAppWidgetIds still returns a list containing among others the id of the widget you just deleted.

Is there a way to retrieve the ids of only the widgets that are active on the homescreen?


回答1:


I ran into this as well. I'm guessing that getAppWidgetIds is simply programmed to always get all IDs ever associated with that widget provider. To solve this, I had to save the Widget ID to my shared preferences by saving the id in the onUpdate method and deleting it in the onDelete method of my AppWidgetProvider.

public class MyProvider extends AppWidgetProvider {
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { 
        // Update your widget as normal

        // If the Id isn't already saved to your db/app preference, save it now
    }

    public void onDeleted (Context context, int[] appWidgetIds) {
        // Remove each id passed in through appWidgetIds 
        // "un-save" them from your db or app preferences
    }
}


来源:https://stackoverflow.com/questions/12462696/appwidgetmanager-getappwidgetids-returning-old-widget-ids

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!