编辑:我安装了我的 app 4.x 设备,没有问题。问题仅存在于 3.x 设备。
当设备上的用户设置发生更改时,我正在尝试手动更新 AppWidget。为此,我使用与此类似的代码:
ComponentName thisWidget = new ComponentName(this, MyAppWidget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(this);
manager.updateAppWidget(thisWidget, updateViews);
我可以说我的 AppWidget onUpdate 方法被调用,因为我在代码中记录了一些调试字符串到 logcat。但是 AppWidget 本身不会在屏幕上改变。
有趣的部分来了:如果我旋转我的设备并强制刷新主屏幕(从 PORTRAIT 到 LANDSCAPE,反之亦然),那么最后我的 AppWidget 就会更新。但是旋转设备不会触发调用 onUpdate 方法,因此 AppWidget 必须使用早期更新中提供的 RemoteViews。
有人可以解释我在处理更新时如何强制我的 AppWidget 的主屏幕重绘吗?
我在用<uses-sdk android:minSdkVersion="11" />
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
// Get all ids
ComponentName thisWidget = new ComponentName(context, MyProvider.class);
int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
// Build the intent to call the service
Intent intent = new Intent(context.getApplicationContext(), MyService.class);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, allWidgetIds);
RemoteViews views = new RemoteViews(context.getPackageName(),R.layout.appwidget_layout);
appWidgetManager.updateAppWidget(appWidgetIds, views);
// Update the widgets via the service
context.startService(intent);
}
我的服务:
@Override
public void onStart(Intent intent, int startId) {
Log.i(LOG, "Called");
this.appWidgetManager = AppWidgetManager.getInstance(this.getApplicationContext());
this.allWidgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
ComponentName thisWidget = new ComponentName(getApplicationContext(), MyProvider.class);
int[] allWidgetIds2 = appWidgetManager.getAppWidgetIds(thisWidget);
Log.w(LOG, "From Intent" + String.valueOf(allWidgetIds.length));
Log.w(LOG, "Direct" + String.valueOf(allWidgetIds2.length));
config = getResources().getConfiguration();
for (int widgetId : allWidgetIds) {
//do things like starting ASYNCs (couple of them) to fetch data from server
//and set an adapter for the gridview
}
Intent intentOpen = new Intent(getApplicationContext(), MainFragmentActivity.class);
PendingIntent open = PendingIntent.getActivity(getApplicationContext(), 0, intentOpen, 0);
remoteViews.setOnClickPendingIntent(R.id.widget_whole, open);
remoteViews.setViewVisibility(R.id.widgetProgress, View.GONE);
appWidgetManager.updateAppWidget( thisWidget, remoteViews );
Log.d(LOG, "sent!!");
}
stopSelf();
super.onStart(intent, startId); }