[英]How to allow only a single instance of a widget android
我想允许添加单个小部件,我尝试放置一个布尔标志,并且我有:
在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,并检查已在配置活动中添加了多少。
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
}
我通常会这样做,以检查我的小部件是否有任何实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.