AppWidget在第一次添加时没有完成更新



编辑:我安装了应用程序4.x设备,没有问题。问题仅存在于3.x设备

当用户设置设备上的更改。为此,我使用类似于以下代码:

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); }

对我来说,这听起来像是启动器应用程序中的一个错误。每次调用updateAppWidget时,AppWidgetManager都会接收到新布局,启动器负责用这个新布局重新绘制小部件。

当屏幕旋转时,不会调用onUpdateupdateAppWidget,但启动器会用其新布局重新绘制小部件,这意味着AppWidgetManager已经成功接收到该新布局。

当屏幕旋转时,启动器被迫重新绘制所有内容(其"活动"被重新创建),这就是它显示新布局的原因。

这个错误可能在Android 4.0+中得到了修复

我会尝试在小部件的视图上调用invalidate()。调用会强制系统重新绘制视图。

最新更新