如何只允许一个小部件android的单个实例

时间:2013-09-25 15:40:52

标签: java android android-appwidget

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

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

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

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

1 个答案:

答案 0 :(得分:1)

直接从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
    } 

这就是我通常要检查我的小部件是否有任何实例。