@Glitch提出的方案在某些情况下可能不适用,特别是对于带有ListView
的应用程序小部件。这是因为ListView
会变得非常缓慢(尝试滚动ListView
),在多次调用appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetId, list_id)
之后。
我猜测,单个RemoteView
实例将在列表中保留其所有执行指令。随着时间的推移,指令列表将增长。每次调用appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetId, list_id)
时,都会重新执行大型指令列表。
我的解决方案如下。但是,我相信它只能在某些设备上运行,因为并非所有设备在启动器重新启动期间都会收到相同的广播消息。
@SuppressLint("NewApi")
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals("com.sec.android.widgetapp.APPWIDGET_RESIZE")) {
handleTouchWiz(context, intent);
handleLauncherRestart(context, intent);
} else if (action.equals("android.appwidget.action.APPWIDGET_UPDATE_OPTIONS")) {
handleLauncherRestart(context, intent);
}
super.onReceive(context, intent);
}
private void handleLauncherRestart(Context context, Intent intent) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
updateAppWidget(context, appWidgetManager, appWidgetId);
}
private void handleTouchWiz(Context context, Intent intent) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
int appWidgetId = intent.getIntExtra("widgetId", 0);
int widgetSpanX = intent.getIntExtra("widgetspanx", 0);
int widgetSpanY = intent.getIntExtra("widgetspany", 0);
if (appWidgetId > 0 && widgetSpanX > 0 && widgetSpanY > 0) {
Bundle newOptions = new Bundle();
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
newOptions.putInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT, widgetSpanY * 74 - 2);
newOptions.putInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH, widgetSpanX * 74 - 2);
} else {
newOptions.putInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT, widgetSpanY * 70 - 30);
newOptions.putInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH, widgetSpanX * 70 - 30);
}
onAppWidgetOptionsChanged(context, appWidgetManager, appWidgetId, newOptions);
}
}