Android主屏幕小部件未更新
Posted
技术标签:
【中文标题】Android主屏幕小部件未更新【英文标题】:Android home screen widget not updating 【发布时间】:2017-02-19 07:49:45 【问题描述】:我创建了一个简单的主屏幕小部件,用于显示从数据库生成的名称。我在TextView中添加了一个刷新名称的按钮,但问题是小部件没有更新。
这是我的 Widget 类:
public class QuotesWidgets extends AppWidgetProvider
ComponentName watchWidget;
RemoteViews remoteViews;
private static final String SYNC_CLICKED = "automaticWidgetSyncButtonClick";
void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
int appWidgetId)
Realm mRealm;
mRealm=Realm.getDefaultInstance();
Random random = new Random();
RealmResults<names> randomName = mRealm.where(Names.class).findAll();
Names name = randomName.get(random.nextInt(randomName.size()));
String name1 = quote.getName();
remoteViews = new RemoteViews(context.getPackageName(), R.layout.my_widget);
watchWidget = new ComponentName(context, MyWidget.class);
remoteViews.setTextViewText(R.id.textview, name);
remoteViews.setOnClickPendingIntent(R.id.refresh, getPendingSelfIntent(context, SYNC_CLICKED));
appWidgetManager.updateAppWidget(watchWidget, remoteViews);
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds)
// There may be multiple widgets active, so update all of them
for (int appWidgetId : appWidgetIds)
updateAppWidget(context, appWidgetManager, appWidgetId);
@Override
public void onReceive(Context context, Intent intent)
super.onReceive(context, intent);
if (SYNC_CLICKED.equals(intent.getAction()))
Realm mRealm;
mRealm=Realm.getDefaultInstance();
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
remoteViews = new RemoteViews(context.getPackageName(), R.layout.quotes_widgets);
watchWidget = new ComponentName(context, MyWidgets.class);
appWidgetManager.updateAppWidget(watchWidget, remoteViews);
Random random = new Random();
RealmResults<names> randomName = mRealm.where(Names.class).findAll();
Names name = randomName.get(random.nextInt(randomName.size()));
String name1 = quote.getName();
Toast.makeText(context,name1, Toast.LENGTH_SHORT).show();
remoteViews.setTextViewText(R.id.textview, name1);
protected PendingIntent getPendingSelfIntent(Context context, String action)
Intent intent = new Intent(context, getClass());
intent.setAction(action);
return PendingIntent.getBroadcast(context, 0, intent, 0);
我在示例中使用了 Toast 消息,当我单击按钮时,Toast 消息每次都会以不同的名称出现,因此除了小部件中 TextView 的更改外,一切都运行良好。有什么问题?
【问题讨论】:
【参考方案1】:先设置新文本:
remoteViews.setTextViewText(R.id.textview, name1);
然后让AppWidgetManager
更新小部件:
appWidgetManager.updateAppWidget(watchWidget, remoteViews);
【讨论】:
以上是关于Android主屏幕小部件未更新的主要内容,如果未能解决你的问题,请参考以下文章