小部件不会更新/重绘
Posted
技术标签:
【中文标题】小部件不会更新/重绘【英文标题】:Widget Wont Update / Redraw 【发布时间】:2020-02-22 12:32:59 【问题描述】:我有一个从 SQLite 加载图像的小部件。每当我添加或删除项目但图像未更新时,它都会更新。我已经尝试向 AppWidgetProvider 类发送广播,但也没有用。
扩展 AppWidgetProvider 的类
private static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId)
Intent intent = new Intent(context, StackWidgetService.class);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.fav_movie_widget);
views.setRemoteAdapter(R.id.stack_view, intent);
views.setEmptyView(R.id.stack_view, R.id.empty_view);
Intent toastIntent = new Intent(context, FavMovieWidget.class);
toastIntent.setAction(FavMovieWidget.TOAST_ACTION);
toastIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
PendingIntent toastPendingIntent = PendingIntent.getBroadcast(context, 0, toastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
views.setPendingIntentTemplate(R.id.stack_view, toastPendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, views);
Log.e(TAG, "onUpdate2: start" );
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds)
Log.e(TAG, "onUpdate: start" );
for (int appWidgetId : appWidgetIds)
updateAppWidget(context, appWidgetManager, appWidgetId);
更新活动
Context context = getApplicationContext();
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
ComponentName thisWidget = new ComponentName(context, FavMovieWidget.class);
int[] appWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.stack_view);
我已经尝试过的
Intent intent = new Intent(this, FavMovieWidget.class);
intent.setAction(appWidgetManager.ACTION_APPWIDGET_UPDATE);
int[] ids = appWidgetManager.getAppWidgetIds(new ComponentName(getApplication(), FavMovieWidget.class));
intent.putExtra(appWidgetManager.EXTRA_APPWIDGET_IDS, ids);
sendBroadcast(intent);
小部件图像未更新 preview widget
【问题讨论】:
【参考方案1】:通过在 updateAppWidget 上添加这个来完成。 这将在我的服务上触发 onGetViewFactory。
Random random = new Random();
intent.setType(String.valueOf(random.nextInt(1000)));
并在我的活动中使用 sendbroadcast
Intent intent = new Intent(this, FavMovieWidget.class);
intent.setAction(appWidgetManager.ACTION_APPWIDGET_UPDATE);
int[] ids = appWidgetManager.getAppWidgetIds(new ComponentName(getApplication(), FavMovieWidget.class));
intent.putExtra(appWidgetManager.EXTRA_APPWIDGET_IDS, ids);
sendBroadcast(intent);
【讨论】:
以上是关于小部件不会更新/重绘的主要内容,如果未能解决你的问题,请参考以下文章