AppWidgetManager getAppWidgetIds返回老控件的ID控件、AppWidgetManager、getAppWidgetIds、ID

2023-09-04 12:42:40 作者:独守一座空城

我试图让我的小部件的所有活动实例的列表。在我AppWidgetProvider的的OnUpdate方法,我做了以下内容:

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);

现在的问题是,如果你添加一个小部件您的主屏幕,然后将其删除,getAppWidgetIds还是返回包含其中包括刚删除的微件的ID列表。

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?

推荐答案

我碰到了这一点。我猜getAppWidgetIds简单编程来总是不断与该插件提供者相关联的所有标识。为了解决这个问题,我不得不Widget的ID保存到我的共享preferences通过保存在的onupdate 法的ID并删除它在 onDelete 我AppWidgetProvider的方法。

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
    }
}