问题
How could I restrict Android widgets in a way that only one instance can be created by the user at all times?
A possible way is to store a SharedPreference
including a counter
variable and crash, if the count is 1, but obviously I'm not in favor of that solution. ;-)
回答1:
How could I restrict Android widgets in a way that only one instance can be created by the user at all times?
You can't.
However, just because the user asks for multiple instances of your app widget does not mean you have to manage separate data for each. Just ignore the IDs and use the updateAppWidget()
method that does not take any IDs.
回答2:
I do like this:
On Widget onUpdate method when user create first widget I save the ID of widget and update widget, for second time when onUpdate is called ( when added widget is updated ) then I check for the same id of widget and update it else tell the user that only one widget is allowed.
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
for (int appWidgetId : appWidgetIds) {
//TinyDb is SharedPreferences Class
TinyDB tinydb = new TinyDB(context);
int WidgetId= tinydb.getInt("WidgetID",-1);
//Check if WidgetID is same as Added ID if yes UPDATE
if (WidgetId == appWidgetId){
updateAppWidget(context, appWidgetManager, appWidgetId);
return;
//Check if no widget is added then add widget and save widget ID to sharedPreferences
} else if (WidgetId == -1){
tinydb.putInt("WidgetID", appWidgetId);
updateAppWidget(context, appWidgetManager, appWidgetId);
return;
}
else
{
//Make toast to tell the user that only one widget is allowed
Toast.makeText(context, context.getResources().getString(R.string.Only_one_widget_allowed), Toast.LENGTH_SHORT).show();
}
}
}
And don't forget: if user remove all widgets to save it to shared preferences, I use int -1 so I use this code:
@Override
public void onDisabled(Context context) {
// Enter relevant functionality for when the last widget is disabled
TinyDB tinydb = new TinyDB(context);
tinydb.putInt("WidgetID", -1);
}
and it works like a charm! Wholaa!
来源:https://stackoverflow.com/questions/4552505/restrict-android-widget-to-one-instance-per-device