2

我想允许添加一个小部件,我尝试放置一个布尔标志,我有:

在 WidgetConfig 内部:

public final static String ADDED_KEY = "IsAdded";
public static boolean isAdded = false;

onCreate(在 WidgetConfig 内)

isAdded = prefs.getBoolean(ADDED_KEY, false);       
    if (isAdded){
        Toast.makeText(this.getApplicationContext(), "Only one Widget", Toast.LENGTH_SHORT).show();
        finish();
    }
 [...]
editor.putBoolean(ADDED_KEY, true); //disable adding here
editor.commit();

WidgetProvider 内部扩展了 AppWidgetProvider

public void onDisabled(Context context) {

    super.onDisabled(context);
    [...]
//cancel alarm
   configEditor.putBoolean(WidgetConfig.ADDED_KEY, false); //enable adding here
    configEditor.commit();
}

public void onDeleted(Context context, int[] appWidgetIds){
super.onDeleted(context, appWidgetIds);
//I should not need this if there is only one widget
}

但它并不总是有效。我能怎么做?谢谢

4

1 回答 1

0

直接从 AppWidgetManager 获取您添加的小部件的 Id,并检查您的配置活动中已经添加了多少。

int[] ids = AppWidgetManager.getInstance(getApplicationContext()).getAppWidgetIds(
            new ComponentName(getApplicationContext(), YOUR_WIDGET.class));

    if(ids.length > 0){
        //do not add the widget
    }else{
        //add the widget
    } 

这就是我通常用来检查我的小部件是否有任何实例的方法。

于 2013-10-02T07:19:13.603 回答