我想允许添加一个小部件,我尝试放置一个 boolean 标志并且我有:
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
}
但它并不总是有效。 我能怎么做?谢谢
最佳答案
直接从 AppWidgetManager 获取您添加的小部件的 ID,并检查您的配置 Activity 中已经添加了多少。
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
}
这就是我检查是否有任何我的小部件实例的通常做法。
关于java - 如何只允许小部件android的单个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19009349/