我有一个配置活动,一个大型小部件提供程序和一个小小部件提供程序。从配置活动中,我在共享首选项中保存了一些值。从大型和小型应用小部件提供商,我得到这些共享的偏好。我无法为应用程序小部件提供唯一的ID,并且我希望每次从配置活动转移到应用程序小部件提供程序时都有不同的共享首选项。我怎样才能做到这一点。
答案 0 :(得分:5)
要为app小部件的每个实例提供唯一的小部件ID,您可以执行以下操作:
AppWidgetManager appWidgetManager = AppWidgetManager
.getInstance(ConfigurationActivity.this);
ComponentName thisAppWidget = new ComponentName(
ConfigurationActivity.this, WidgetProvider.class);
int[] appWidgetIds = appWidgetManager
.getAppWidgetIds(thisAppWidget);
Intent startBroadcast = new Intent(ConfigurationActivity.this,
WidgetProvider.class);
startBroadcast.putParcelableArrayListExtra("list", newsList);
startBroadcast.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,
appWidgetIds);
startBroadcast.setAction("android.appwidget.action.APPWIDGET_UPDATE");
sendBroadcast(startService);
为了以唯一共享首选项保存数据,您可以执行以下操作:
public void setWidgetNewsCategory(Context context, String category,
int appWidgetId) {
Editor editor = context.getSharedPreferences(
PREFS_NAME_CATEGORY + String.valueOf(appWidgetId),
Context.MODE_PRIVATE).edit();
editor.putString(PREFS_VALUE_CATEGORY + String.valueOf(appWidgetId),
category);
editor.commit();
}
您可以按如下方式检索此共享的pref值:
public String getWidgetNewsCategory(Context context, int appWidgetId) {
SharedPreferences sharedPreferences = context.getSharedPreferences(
PREFS_NAME_CATEGORY + String.valueOf(appWidgetId),
Context.MODE_PRIVATE);
return sharedPreferences.getString(
PREFS_VALUE_CATEGORY + String.valueOf(appWidgetId), null);
}
最后,在Widget Provider的onReceive方法中,执行以下操作:
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) {
Bundle extras = intent.getExtras();
if (extras != null) {
int[] appWidgetIds = extras
.getIntArray(AppWidgetManager.EXTRA_APPWIDGET_IDS);
if (appWidgetIds.length > 0) {
this.onUpdate(context, AppWidgetManager.getInstance(context), appWidgetIds);//here you can call onUpdate method, and update your views as you wish
}
}
} else if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
Bundle extras = intent.getExtras();
if (extras != null
&& extras.containsKey(AppWidgetManager.EXTRA_APPWIDGET_ID)) {
final int appWidgetId = extras
.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID);
this.onDeleted(context, new int[] { appWidgetId });
}
} else if (AppWidgetManager.ACTION_APPWIDGET_ENABLED.equals(action)) {
this.onEnabled(context);
} else if (AppWidgetManager.ACTION_APPWIDGET_DISABLED.equals(action)) {
this.onDisabled(context);
}
}
这只是对我有用的一般解决方案。希望它也适合你。